![](/img/trans.png)
[英]Question regarding returning a null value in a then callback of a promise in firebase cloud functions
[英]Google cloud functions: functions.https.onCall returning null but the value is shown correctly in the logs
我正在通過 Axios async-await 調用第三方 API,並通過谷歌雲 function 將結果返回給 flutter 應用程序。我被迫使用functions.https.onCall
,因為onRequest
無法調用 7888知道。
結果在雲 function 的日志中的console.log
中正確顯示,但是當 flutter 應用程序調用 function 時,它總是收到null
。 為什么?
getSmsBalance: functions.https.onCall(async (data, context) => {
const business_id = data.business_id;
const collectionRef = db.collection("buser_sms");
const snapshot = await collectionRef.where("id", "==", business_id).get();
if (snapshot.empty) {
console.log("No matching documents - getSMSBalance .");
let response = {
status: false,
};
return JSON.stringify(response);
}
snapshot.forEach((doc) => {
if (
doc.data().enableReservationSms == true ||
doc.data().enableAutoReminder == true ||
doc.data().enableReminderSms == true
) {
// get balance
(async () => {
const balance = await getBalance(
doc.data().senderId,
doc.data().username,
doc.data().password
)
.then((result) => {
let response = {
status: true,
data: result,
};
console.log("balance is " + result);
return JSON.stringify(response);
})
.catch((err) => {
console.error(`Error - getSmsBalance - ${err}`);
let response = {
status: false,
};
return JSON.stringify(response);
});
})();
}
});
}),
您的代碼存在幾個問題:
Array.forEach
中使用 async/await 語法,由於其固有設計,它不允許等待。 如果你想在循環迭代中使用異步/等待,你需要使用Array.map
例如。 但在大多數情況下,您不應該在循環內使用 async/await,因為它消除了異步代碼執行的優勢(每次迭代僅在前一次迭代之后觸發)。snapshot.empty
。 then
和catch
回調中的return
僅將值分配給之后不使用的變量balance
。所以總而言之,你需要使用類似的東西:
return Promise.all(
snapshot.map((doc) => {
return getBalance(
doc.data().senderId,
doc.data().username,
doc.data().password
)
.then((result) => {
let response = {
status: true,
data: result,
};
console.log('balance is ' + result);
return JSON.stringify(response);
})
.catch((err) => {
console.error(`Error - getSmsBalance - ${err}`);
let response = {
status: false,
};
return JSON.stringify(response);
});
})
);
請注意,我提供的代碼被截斷了,沒有考慮您實際需要的格式,如 output。擁有一個response
數組可能不是您所需要的。 但是您最終應該能夠根據您的需要調整該代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.