gpt4 book ai didi

node.js - 如何从 Firebase 函数中为 Google 上的 Actions 调用第三方 Rest API

转载 作者:太空宇宙 更新时间:2023-11-04 03:20:53 24 4
gpt4 key购买 nike

我正在尝试从 Firebase 函数调用 Rest API,该函数作为 Actions on 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”完成,并且我从 Actions on Google 收到错误,表示没有响应。错误发生后,我可以在 Firebase 日志中看到 console.log 输出,因此一切正常,只是不同步。

我尝试使用 async/await 但收到错误,我认为这是因为 Firebase 使用不支持异步的旧版本的 node.js。

我该如何解决这个问题?

最佳答案

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

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.');
});
});

关于node.js - 如何从 Firebase 函数中为 Google 上的 Actions 调用第三方 Rest API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50538121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com