如何确保解决可变数量的 Promise 返回函数?

How to make sure a variable amount of Promise returning functions is resolved?

我在构建我的异步代码时遇到了问题。所有数据库操作都是异步的和 return Promises。

我需要在数据库中找到一堆项目,更改它们,然后保存它们,只有在所有都保存之后,才能继续我程序流程中的下一步。

如何使用 ES6 promises 解决这个问题?

这是一些伪代码来说明我的问题:

 database.find("Items").then(results => {
   results.forEach(result => {
      result.name = "some different name";
      database.save(result) // <-- is also async as find
   });
   return true;
 }).then(next) {
   // Only start here after all database.save() have been resolved
 });

您可以使用 Promise.all():

database.find("Items").then(results => {
   return Promise.all(results.map(result => {
      result.name = "some different name";
      return database.save(result) // <-- is also async as find
   }));
 }).then(() => {
   // Only start here after all database.save() have been resolved
 });

使用 Promise.all 等待多个承诺 - 它需要一个承诺数组(可变长度)。

database.find("Items").then(results => {
    var promises = results.map(result => {
//                         ^^^
        result.name = "some different name";
        return database.save(result);
//      ^^^^^^
    });
    return Promise.all(promises);
}).then(saves => {
//      ^^^^^ an array of the results from the save operations
    …; // starts after all database.save() promises have been resolved
});