我一直在工作,直到在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(() => {
//...
})
我非常感谢我能从中获得的所有帮助,干杯!
最佳答案
如果您想知道何时完成一堆并行操作,请使用数据库上的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
});
})
关于node.js - 在下一条命令之前完成整个循环/forEach,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57528113/