我已经阅读了所有相关的问题,并观看了Firebase的视频《承诺》,但我仍然无法摆脱上述错误。附加的代码在本地运行良好,但当从云函数中完成时,我不断收到这个错误。任何帮助都将不胜感激!
exports.enquiry = functions.firestore.document('users/{userId}/enquiries/{enquiryId}')
.onCreate((snap, context) => {
let enquiryDoc = snap.data();
let {
uid,
type
} = enquiryDoc;
function ResponseGeneration(type) {
switch (type) {
case 'type1':
{
Response = 5;
return Promise.resolve(Response);
}
case 'type2':
{
var body = `<QUOTA><DATE>20181203</DATE></QUOTA>`;
const call = request.post({
url: "xxx",
port: 443,
method: "POST",
headers: {
'Content-Type': 'text/xml',
},
body: body,
json: false
})
.then((parsedBody) => {
console.log(parsedBody.statusCode);
console.log(parsedBody);
return xml2js(parsedBody);
})
.then((js) => {
console.log('JSON.stringify(js):', JSON.stringify(js));
var json = JSON.stringify(js);
var jsonParsed = JSON.parse(json);
if (jsonParsed.hasOwnProperty('Error')) {
Response = jsonParsed['Error']['Message'];
} else {
Response = jsonParsed['RESULT'];
}
console.log("Response: ", Response);
return Promise.resolve(Response);
}).catch(function(err) {
console.log("error from post:", err);
// return Promise.resolve(err);
});
return Promise.all(call); //also tried with Promise.resolve
}
default:
return Promise.resolve(0.0);
}
}
ResponseGeneration(type).then((response) => {
return snap.ref.update({
quote: response,
status: 'quoted',
quoteId: context.params.enquiryId
});
});
});
正如你所看到的,它到处都返回Promises,但Firestore控制台一直在打印:
Function returned undefined, expected Promise or value
我不太明白它还有什么地方可能会错过承诺。有什么帮助吗?
onCreate()
调用的顶级函数没有返回任何内容,因此出现错误。
您需要将呼叫中的Promise
返回给ResponseGeneration
:
return ResponseGeneration(type).then((response) => {
return snap.ref.update({
quote: response,
status: 'quoted',
quoteId: context.params.enquiryId
});
});