Node.js 如何从Firebase函数调用第三方RESTAPI来执行Google上的操作

Node.js 如何从Firebase函数调用第三方RESTAPI来执行Google上的操作,node.js,firebase,actions-on-google,dialogflow-es,Node.js,Firebase,Actions On Google,Dialogflow Es,我试图调用Firebase函数中的RESTAPI,该函数作为Google上操作的实现提供服务器 我尝试了以下方法: const { dialogflow } = require('actions-on-google'); const functions = require('firebase-functions'); const http = require('https'); const host = 'wwws.example.com'; const app = dialogflow({

我试图调用Firebase函数中的RESTAPI,该函数作为Google上操作的实现提供服务器

我尝试了以下方法:

const { dialogflow } = require('actions-on-google');
const functions = require('firebase-functions');
const http  = require('https');
const host = 'wwws.example.com';

const app = dialogflow({debug: true});

app.intent('my_intent_1', (conv, {param1}) => {

         // Call the rate API
        callApi(param1).then((output) => {
            console.log(output);
            conv.close(`I found ${output.length} items!`); 
        }).catch(() => {
            conv.close('Error occurred while trying to get vehicles. Please try again later.'); 
        });

});

function callApi (param1) {
    return new Promise((resolve, reject) => {
        // Create the path for the HTTP request to get the vehicle
        let path = '/api/' + encodeURIComponent(param1);
        console.log('API Request: ' + host + path);


        // Make the HTTP request to get the vehicle
        http.get({host: host, path: path}, (res) => {
            let body = ''; // var to store the response chunks
            res.on('data', (d) => { body += d; }); // store each response chunk
            res.on('end', () => {
                // After all the data has been received parse the JSON for desired data
                let response = JSON.parse(body);
                let output = {};

                //copy required response attributes to output here

                console.log(response.length.toString());
                resolve(output);
            });
            res.on('error', (error) => {
                console.log(`Error calling the API: ${error}`)
                reject();
            });
        }); //http.get
    });     //promise
}

exports.myFunction = functions.https.onRequest(app);
这几乎奏效了。API被调用,我得到了数据。问题是,如果没有async/await,函数就不会等待“callApi”完成,我从Google上的操作中得到一个错误,即没有响应。错误发生后,我可以在Firebase日志中看到console.log输出,因此一切正常,只是不同步

我尝试使用async/await,但出现了一个错误,我认为这是因为Firebase使用了旧版本的node.js,它不支持异步


我该如何解决这个问题呢?

您的函数
callApi
返回一个承诺,但在意图处理程序中不返回承诺。您应该确保添加
返回
,以便处理程序知道等待响应

app.intent('my_intent_1', (conv, {param1}) => {
     // Call the rate API
    return callApi(param1).then((output) => {
        console.log(output);
        conv.close(`I found ${output.length} items!`); 
    }).catch(() => {
        conv.close('Error occurred while trying to get vehicles. Please try again later.'); 
    });
});

承诺<代码>然后工作正常。