【问题标题】:How to run a for loop for promises in node.js如何在 node.js 中为 Promise 运行 for 循环
【发布时间】:2019-01-18 17:12:31
【问题描述】:

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

在下面的代码中,directoryName 是一个 promise 的结果。这基本上是一个目录名称数组。在 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 并将其结果存储在全局数组中?

【问题讨论】:

    标签: javascript node.js for-loop ecmascript-6 promise


    【解决方案1】:

    您需要使用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
      });
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2020-03-01
      • 2016-02-22
      • 1970-01-01
      • 2018-05-11
      • 2019-01-07
      相关资源
      最近更新 更多