node.js - 在下一个命令之前完成整个循环/forEach
问题描述
我一直在工作,直到我在 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
});
})
推荐阅读
- assembly - 我们应该在汇编中将长字符串存储在堆栈中吗?
- windows - Visual Studio 未加载符号并显示错误:。无法找到或打开 PDB 文件。即使 PDB 存在于符号服务器中
- python - 安装 Ray 时出现 Python PIP 问题 - Wheel 包不可用
- python - Telegram Bot(用 python 编码)与 AWS API Gateway 集成
- laravel - Opacity 属性只出现在 Docker 容器中
- python - python数据框collect()函数
- amazon-web-services - 在 Azure 应用服务和 AWS ECS 服务之间建立私有安全连接的最佳方式
- python - pm2在启动python程序后显示错误
- java - 如何更准确地测量单向网络延迟?
- java - 如何在 Spring Java 中解码 Outlook 中的 html 电子邮件?