【发布时间】:2020-02-27 07:14:15
【问题描述】:
我在 firebase 云功能中遇到了一种情况,其中只执行了 FIRST console.log 或 firestore 更新语句。
我还有其他类似的功能,响应的处理方式略有不同,但这没有任何问题
我已经检查了谷歌云控制台/firebase 控制台等,源代码似乎已正确上传
exports.myFunction = functions.firestore.document(docPath).onCreate(async (snapshot, context) => {
var inputData = snapshot.data();
console.log('printing request');
console.log(inputData);
//Prepare to call the api
var data = {'input': 'some value'};
var resource = 'api_resource';
// call api - below function is provided by an external provider and takes a callback function once api call is complete
myApi.call(resource, data.input, function (error, result) {
if (error) {
console.log('Error from api');
return { status: 'error', code: 401, message: 'Error from api' }
}
var apiResult = JSON.parse(result);
console.log('printing api response'); // <-- Anything below this does not get executed. When this is removed, next line is executed and so on
console.log(apiResult);
//Write to Firestore
snapshot.ref.update({
'status': 'computed',
})
.then((a) => {
console.log('Written successfully to db');
return 0;
})
.catch(err => {
console.log('Error setting db' + err);
return { status: 'error', code: 401, message: 'Error setting db ' }
});
// console.log('End of function');
return { status: 'success', code: 200, message: 'Completed successfully' }
});
});
我看到另一个post 与这种情况相反。有人知道为什么会这样吗?
【问题讨论】:
-
我怀疑您对回调的处理发生了一些事情,因为 Cloud Functions 不支持 background activities,除非您实际上返回了一个承诺。你能promisify你正在调用的API并返回整个链吗?基本上,当顶级函数返回时,您可以期望在该 api 调用后不久停止处理。
-
@robsiemb 感谢您的回复。我有同样的预感,除了具有类似回调函数的相同 api 调用执行没有问题。让我试试你的建议