首页 > 解决方案 > 如何在 node.js 中为 Promise 运行 for 循环

问题描述

我有一个返回承诺的函数。Promise 实际上读取一个 JSON 文件并将该文件的一些数据推送到一个数组中并返回该数组。我可以使用单个文件来执行此操作,但我想运行具有多个文件路径的 for 循环,并希望将每个 Promise 的所有结果(解析)推送到一个数组中。正确的做法是什么?

在以下代码中,directoryName 是一个承诺的结果。这基本上是一个目录名称数组。在 secondMethod 函数中,我仅使用数组中的第一个目录名称来操作该目录中的文件。假设数组中的每个目录都有 t.json 文件。

let secondMethod = function(directoryName) {
    let promise = new Promise(function(resolve, reject) {
        let tJsonPath = path.join(directoryPath, directoryName[0], 't.json')
        jsonfile.readFile(tJsonPath, function(err, obj) {
            let infoRow = []
            infoRow.push(obj.name, obj.description, obj.license);
            resolve(infoRow)
        })
    }
    );
    return promise;
}

如何在 directoryName 数组上运行循环,以便为数组的每个元素执行 jsonfile.readFile 并将其结果存储在全局数组中?

标签: javascriptnode.jsfor-loopecmascript-6promise

解决方案


您需要使用Promise.all将每个名称映射到Promise. 还要确保检查reject以防出现错误:

const secondMethod = function(directoryName) {
  return Promise.all(
    directoryName.map((oneName) => new Promise((resolve, reject) => {
      const tJsonPath = path.join(directoryPath, oneName, 't.json')
      jsonfile.readFile(tJsonPath, function(err, obj) {
        if (err) return reject(err);
        const { name, description, license } = obj;
        resolve({ name, description, license });
      })
    }))
  );
};

// Invoke with:
secondMethod(arrOfNames)
  .then((results) => {
    /* results will be in the form of
    [
      { name: ..., description: ..., license: ... },
      { name: ..., description: ..., license: ... },
      ...
    ]
    */
  })
  .catch((err) => {
    // handle errors
  });

推荐阅读