簡體   English   中英

如何在node.js中為諾言運行for循環

[英]How to run a for loop for promises in node.js

我有一個返回承諾的函數。 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並將其結果存儲在全局數組中?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM