今天突然部署我的功能后,我们的一些功能突然总是超时。我在云功能控制台中看到了这一点。这似乎发生在嵌套和返回承诺时。奇怪的是,这种情况从未发生过。
这是我的代码。
exports.pushMessageQueue = functions.database.ref('/userPushMessagesQueue/{userId}/{messageId}').onWrite(event => {
if (!event.data.exists()) {
console.log('DOES NOT EXIST!');
return "not exists";
}
console.log("EXISTS!");
const userId = event.params['userId'];
const messageId = event.params['messageId'];
const payload = event.data.val();
return database.ref('devices').orderByChild('user_id').equalTo(userId).once('value', snapshot => {
if (!snapshot.exists()) {
return "no devices found";
}
const devices = snapshot.val();
const deviceTokens = [];
snapshot.forEach(deviceSnap => {
const device = deviceSnap.val();
deviceTokens.push(device['fcm_key']);
});
const removeFromQueue = database.ref(`/userPushMessagesQueue/${userId}/${messageId}`);
console.log('then0');
return removeFromQueue.set(null).then(() => {
console.log('then1');
return admin.messaging().sendToDevice(deviceTokens, payload).then(() => {
console.log('then2');
return "send";
});
}, (error) => {
console.log('error1!');
console.log(error);
});
});
});
在控制台中记录then0,而不是then1然后是2。当我收到推送通知时,该条目将从队列中删除。
我做错了吗?
答案 0 :(得分:3)
您正在返回once()函数,而不是promise链。
基本上,你已写过:
//returns the once promise
return ref.once('value', function(snap) {
/* some stuff that doesn't affect the promise chain happens here */
});
当你想要的是这个:
// returns whatever happens in the .then() callback
return ref.once('value').then(snap => {
/* now whatever you return here affects the promise chain */
});