node.js - 函数在 Promise 结束之前完成
问题描述
我正在尝试实现实际的SendPush 函数,以便向200 个用户发送推送通知,然后处理sendToDevice() 的结果。问题是即使我用 Promise 包装了所有异步代码,云函数仍然在 sendToDevice().then 执行的 console.log 之前完成。一些推送通知也没有到达目的地。
在调用 actualSendPush 时,我也在使用 Promise。这段代码有什么缺陷?
function actualSendPush(fcmKey, volId, title, msg, evtId, orgId, url){
const promises = [];
console.log("notifying user about msg ", fcmKey, " ", msg);
const payload = {
notification: {
title: "Help Required",
body: title,
sound:"default",
click_action: "FLUTTER_NOTIFICATION_CLICK"
},
data: {
title : title,
msg : msg,
eventId : evtId
}
};
return Promise.all([admin.messaging().sendToDevice(fcmKey, payload)
.then(function (response) {
// event push success counter
if (response.successCount == 1)
{
console.log("Successfully sent message:", response);
promises.push(incrementTransaction("events/" + orgId + "/" + evtId + "/numEventsSendSuccess"));
}
else
{
console.log("Failed sent message:", response);
promises.push(incrementTransaction("events/" + orgId + "/" + evtId + "/numEventsSendFail"));
}
/*var updates = {};
updates["eventUserReqs/" + orgId + "/" + evtId + "/users/" + volId + "/status"] = response.successCount; // 0 failed 1 success
admin.database().ref().update(updates);*/
// The user might have opened the push before the server side had the chance to change the status to successful or not.. if it
// already has a value, don't change it.
var dbRef = admin.database().ref("eventUserReqs/" + orgId + "/" + evtId + "/users/" + volId + "/status");
promises.push(dbRef.transaction(function (current_value) {
return current_value != null ? current_value : (response.successCount);
}));
return Promise.all(promises);
})
.catch(function (error) {
console.log("Error sending message:", error);
// event push fail counter
incrementTransaction("events/" + orgId + "/" + evtId + "/numEventsSendFail");
var dbRef = admin.database().ref("eventUserReqs/" + orgId + "/" + evtId + "/users/" + volId + "/status");
return dbRef.transaction(function (current_value) {
return current_value != null ? current_value : 0;
});
})]);
}
解决方案
推荐阅读
- spring-webflux - 继续 zip(),如果一个源已完成
- javascript - 合并两个数组而不覆盖
- matlab - 如何使用 Matlab 读取 3D 文件中的颜色?
- python - 来自外部库的代码覆盖率 python
- powershell - PowerShell Where-Object - 没有返回 - 我一定做错了什么
- javascript - 通过通配符匹配 URL
- python - 在python中为每一天(来自单个时间序列)创建新列
- kotlin - 如何将键和值添加到 Kotlin 中列表的映射?
- gitlab - gitlab heroku api 密钥保护
- javascript - 在屏幕上显示从 firebase 返回的数据