node.js - 如何将 forEach 与 Promises.all 结合起来

标签 node.js mongodb promise

我正在执行一个函数,将图像从输入文件字段上传到AWS,然后将图像URL和名称保存到mongoDB。我正在使用 NodeJS 和 MongoDB。这是我的例子:

uploadFile(req, res, next) {

 let files = req.files;
 let images = [];


  files.file.forEach((file) => {

    uploadToAWS(file.path, {}, function(err, img) {

    if (err) { throw err; }

        // add path and name to images array

        images.push({
          path: img[0].url,
          name: img[0].name,
        });
    });
  });
    // Here the promises should resolve and save to MongoDB the array images
 },

无需在每次循环迭代元素时都保存到数据库,我只需填充一个数组images,然后将其保存到数据库。

最佳答案

为此,您需要使用 Array#map()而不是Array#forEach 。这是因为您打算根据每个值将一些值映射到 promise 。

return Promise.all(files.map((file) => {
    // do some stuff with each file here
}));

完整的示例如下所示:

uploadFile(req, res, next) {
  let files = req.files;
  let images = [];

  const promises = files.file.map((file) => {
    return uploadToAWS(file.path, {}).then((img) => {
      // add path and name to images array

      images.push({
        path: img[0].url,
        name: img[0].name,
      });
    });
  });

  // Here the promises should resolve and save to MongoDB the array images
  Promise.all(promises).then(next);
}

请注意,在这里,我假设 uploadToAws() 能够返回一个 promise ,因为这是完成这项工作所必需的,否则 cards promise 的房子就会崩溃。如果 uploadToAws() 没有对 Promise 的内置支持,您可以使用 promisify 实用程序,例如 pify使用适配器包装该函数,该适配器将根据回调的结果为您创建一个 promise 。

资源

关于node.js - 如何将 forEach 与 Promises.all 结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44175509/

相关文章:

node.js - 当我的 Elastic Beanstalk 环境已配置 HTTPS 时,是否需要将 HTTPS 与 Express 结合使用?

javascript - MediaStream 未处理的 promise 拒绝 : [object DOMError] (in Safari 11)

javascript - 使用finally() 正确构建Javascript Promise

javascript - 如何使用多个 npm 身份验证 token

javascript - 递归 process.nextTick 警告

javascript - 在 Robo3T 中,如何添加自定义功能

javascript - Mongoose 按 createdAt 排序

javascript - Firebase 检索某个子项下的数据

node.js - 用鞋sockjs进行广播

javascript - 如何使用express.js和mongoclient将数组插入mongodb