首页 > 解决方案 > 动态添加到 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
});

标签: javascriptecmascript-6promise

解决方案


我相信您的代码不起作用的主要原因是您将数组数组 ( [services.map(...)]) 传递给Promise.all,而不是承诺数组。

但是,代码过于复杂。无需在函数内部创建承诺asyncasync函数总是返回承诺。它应该只是:

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
  })
)

推荐阅读