我一直让它工作,直到我在forEach后面添加了更多的命令。基本上,当一个帖子被删除时,主要的目标是将它从用户的提要中删除(这是有效的)。然后我链接了4个.then(),现在它只循环一次,然后完成其余的进程……在继续之前,我如何确保它先循环整个集合?
下面是我的代码:
exports.updateFeedDelete = functions.database.ref('/categories/{postId}')
.onDelete((snapshot, context) => {
//...
const followersRef = admin.database().ref(`friends/${friendId}`);
return followersRef.once("value", function(snap) {
snap.forEach(function(childSnapshot) {
const followerId = childSnapshot.key;
//FINISH ALL LOOPS HERE?
return admin.database().ref(`feed/${followerId}/${postId}`).remove();
});
})
//DONT EXECUTE UNTIL ALL LOOPS ARE DONE, NOT ONLY 1...
.then(() => {
//...
})
.then(() => {
//...
})
.then(() => {
//...
})
.then(() => {
//...
})
我很感谢大家对我的帮助,干杯!
发布于 2019-08-16 17:15:49
如果您想知道一大堆并行操作何时完成,请使用数据库上的promise接口获取每个操作的promise,并使用Promise.all()
监视promise数组并告诉您它们何时全部完成,然后在Promise.all()
告诉您一切都已完成时启动代码的其余部分。
我真的不太了解firebase API,但在文档中稍微查看一下,我认为它可能是这样的:
exports.updateFeedDelete = functions.database.ref('/categories/{postId}')
.onDelete((snapshot, context) => {
//...
const followersRef = admin.database().ref(`friends/${friendId}`);
return followersRef.once("value").then(snap =>
let promises = [];
snap.forEach(childSnapshot => {
const followerId = childSnapshot.key;
// do whatever else here. If asynchronous, chain promises
// so you're pushing one promise into the array that
// represents when all this code is done
promises.push(admin.database().ref(`feed/${followerId}/${postId}`).remove());
});
return Promise.all(promises);
}).then(() => {
// code here will run after the snap.forEach() code is done
}).catch(err => {
// handle errors here
});
})
https://stackoverflow.com/questions/57528113
复制相似问题