javascript - 动态添加到 Promise 数组时,Promise 全部提前完成
问题描述
此代码按预期工作:
services.map(async svc => {
promises.push(new Promise(async (resolve) => {
html += `<h2>${svc}</h2>`;
let journeyDetails = await admin.database().ref(`data`).once('value');
resolve();
}));
});
await Promise.all(promises).then(() => {
return res.send(html);
})
为什么下面的代码不起作用?在我看来是一样的,但是现在执行顺序不正确。
Promise.all([
services.map(async svc => {
new Promise(async (resolve) => {
html += `<h2>${svc}</h2>`;
let journeyDetails = await admin.database().ref(`data`).once('value');
resolve();
})
})
]).then(() => {
// done - called before finished in this version
}).catch(() => {
// err
});
解决方案
我相信您的代码不起作用的主要原因是您将数组数组 ( [services.map(...)]
) 传递给Promise.all
,而不是承诺数组。
但是,代码过于复杂。无需在函数内部创建承诺async
,async
函数总是返回承诺。它应该只是:
Promise.all( // <- note the removed [...]
services.map(async svc => {
html += `<h2>${svc}</h2>`;
let journeyDetails = await admin.database().ref(`data`).once('value');
// more code here
})
)
推荐阅读
- python - 迭代循环以获取每个不同日期变量的数据帧变量的 cumsum(非聚合)
- bash - bash 命令可以多长时间?
- c# - 如何在 C# 中以编程方式确定 Windows 7 的子版本?
- python - manage.py runserver后如何自动执行代码
- android - 尝试将 Content Uri 从活动传递到服务时出现权限错误
- macos - 子目录项目的 Composer 卸载 (Mac)
- excel - Excel VBA 中有没有办法检查一个工作簿中的数字序列,找到最后一个,然后在另一个工作簿中继续?
- node.js - 一段时间后,Socket io 连接断开
- c# - 如何访问从asp.net核心中的jquery文件上传发送的附加表单数据?
- r - 如何在 R 中重现以下涉及 for 循环的 matlab 代码?