我有一个HTTP触发的Firebase函数,该函数使用请求库https://github.com/request/request将HTTP发布到另一个API。日志显示POST请求正在返回正确的数据,但Firebase功能在异步POST返回数据之前就已完成。 如何使整体功能等待POST请求?
const functions = require('firebase-functions');
var requestDependency = require('request');
exports.XXXXXXXXXX = functions.https.onRequest((request, response) => {
var answer = 'testo';
var jsonResponse = null;
var jsonData = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
let url = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; //or production
requestDependency.post({
headers: {
'content-type': 'XXXXXXXXXXXXXXXXXXXX' ,
'Accept': 'XXXXXXXXXXXXXXXXXXXX',
'XXXXXXXXXX-Access-Token': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
},
url: url,
body: jsonData
}, function(error, response, body) {
if (error) {
console.log('errrrrrrrror1')
} else {
jsonResponse = body;
console.log(jsonResponse); <-----Shows correct data returned
console.log('Done.');
answer = jsonResponse;
console.log('TEST: ' + answer)
}
});
console.log("Performing search");
response.send(cardName+" "+jsonResponse); <---jsonResponse not populated
});
答案 0 :(得分:2)
根据documentation,当响应发送到客户端时,HTTP函数终止。这意味着您对response.send()的调用有效地终止了该函数。
问题是对post()
的调用是异步的,并且在HTTP请求在后台继续的同时立即返回。发布后,函数将继续执行。这意味着您发送的响应几乎肯定会在HTTP请求完成之前得到执行。
如果要等待HTTP请求完成,请将响应放在客户端内部中,该回调处理HTTP请求的响应。
function(error, response, body) {
if (error) {
console.log('errrrrrrrror1')
// send an error response here
} else {
jsonResponse = body;
console.log(jsonResponse); <-----Shows correct data returned
console.log('Done.');
answer = jsonResponse;
console.log('TEST: ' + answer)
// send an success response here
}
});
也请观看此视频系列,以更好地了解Cloud Functions的工作原理:https://www.youtube.com/watch?v=7IkUgCLr5oA&index=2&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM