我正在尝试执行将推送通知发送到列表中的所有用户的云功能。当列表较小时,此方法效果很好。我认为问题是由于我发送推送请求的电话数量引起的。有什么想法吗?
云功能:
exports.sendPushToUsers = functions.https.onCall((data, response) => {
var promisesSendPushs = [];
return admin.database().ref(Constants.USERS).once("value")
.then((usersSnap) => {
if(usersSnap.exists()) {
usersSnap.forEach(userSnap => {
if(userSnap.exists()) {
var user = userSnap.val();
if(user.firebaseToken !== undefined) {
var promiseSendPush;
if(user.platform === Constants.PLATFORM.IOS) {
promiseSendPush = pushs.customIOS.customized(user.firebaseToken, user.uid, data.title, data.body);
} else {
promiseSendPush = pushs.customAndroid.customized(user.firebaseToken, user.uid, data.title, data.body);
}
promisesSendPushs.push(promiseSendPush);
}
}
});
return Promise.all(promisesSendPushs)
} else {
console.log("usersSnap undefined");
return {code: 0, state: 'undefined'};
}
})
.then(() => {
console.log("promisesSendPushs: " + promisesSendPushs.length)
return {code: 0, state: 'pushs send!'};
})
.catch(err => {
console.log ('Error getting documents', err);
return { code: 1, error: err};
});
})
自定义推送库:
const admin = require('firebase-admin');
function sendPushToUser(firebaseToken, message, uid) {
if(firebaseToken) {
return admin.messaging().sendToDevice(
[ firebaseToken ],
message
).then(() => {
return { code: 0}
})
.catch((err) => {
return { code: 1}
});
} else {
return { code: 1 }
}
}
exports.customized = function(firebaseToken, uid, title, body) {
let message = {
data: {
title: `${title}`,
body: `${body}`
}
};
return sendPushToUser(firebaseToken, message, uid);
};
控制台Firebase错误:
Error: function crashed out of request scope
函数调用被中断。
答案 0 :(得分:1)
您可能不想将所有这些承诺的结果发送给客户:
return Promise.all(promisesSendPushs)
Cloud Functions可能会尝试从所有已解决的Promise序列化所有结果而崩溃,这可能会变得很大。
相反,请确定在所有诺言成功的情况下要发送给客户端的响应。例如:
return Promise.all(promisesSendPushs)
.then(results => {
return { the object to send to the client on success }
})
.catch(error => {
return { the object to send to the client on error }
})