Javascript Node.js等待循环中读取的所有文件

Javascript Node.js等待循环中读取的所有文件,javascript,node.js,Javascript,Node.js,我是javascript/node.js事件驱动范例的新手 我需要停止for after forEach以确保所有文件都已读取,然后继续。在此上下文中,我应该如何实现等待所有文件\u read() my_list.forEach(function(element) { fs.readFile(element.file_path, function(err, data) { if(err) throw err; element.obj=JSON.parse(data);

我是javascript/node.js事件驱动范例的新手

我需要停止for after forEach以确保所有文件都已读取,然后继续。在此上下文中,我应该如何实现
等待所有文件\u read()

my_list.forEach(function(element) {
  fs.readFile(element.file_path, function(err, data)  {
    if(err) throw err;
    element.obj=JSON.parse(data);
  });
});
wait_for_all_files_read(); <-----------
analyze(my_list)
my_list.forEach(函数(元素){
fs.readFile(element.file_路径,函数(err,data){
如果(错误)抛出错误;
element.obj=JSON.parse(数据);
});
});
等待所有文件读取() 我将如何做到这一点:

  • Promisify fs.readFile(通过使用例如Bluebird)
  • 将函数标记为异步
  • 制作回调列表(my_list.map而不是forEach)
  • “等待承诺。全部(myListOfCallbacks)”
  • 等待后的下一行将在所有操作完成后执行
  • 诸如此类:

    const{promissfy}=require('util')
    常量fs=require('fs')
    const readFile=promisify(fs.readFile)
    const fileNames=getFilenamesArray();
    异步函数executeMe(){
    试一试{
    const arrayWithFileContent=wait Promise.all(
    map(name=>readFile(name))
    );
    返回分析(ArrayWithFileContent);
    }
    捕捉(错误){
    手柄错误(err)
    }
    }
    
    executeMe()我可以建议您重写代码以保证-这将使处理它变得非常容易

    const {promisisfy} = require('util')
    const fs = require('fs')
    const readFile = promisify(fs.readFile)
    
    const fileNames = getFilenamesSomehow() // <-- returns array with path, e.g. ["./package.json", "/etc/hosts", "/etc/passwd"]
    
    Promise.all(fileNames.map(name => readFile(name)))
    .then(arrayWithFilesContent => analyze(arrayWithFilesContent))
    .catch(err => handleError(err))
    
    然后假设您需要分析一堆文件

    const fileNames = [...] // array with file names
    // this create an array of promises, each of them read one file and returns the file content in JSON
    const promises = fileNames.map(function (singleFileName) {
        return readFile(singleFileName)
        .then(function (singleFileContent) {
           return JSON.parse(singleFileContent)
        })
    })
    
    // promise all resolves (calls callback in 'then') all of promises in array are resolved and pass to then callback array with result of each promise
    Promise.all(promises)
      .then(function (arrayWithResults) {
        return analyze(arrayWithResults)
      })
      // catch callback calls if one of promises in array rejects with error from the promise - so you can handle e.g. read file error or json parsing error here
      .catch(function (error) {
        //here you can handle any error
        console.log(error)
      })
    
    试着用谷歌搜索一些文章来阅读承诺是如何起作用的。
    例如。您可以启动表单

    我可以使用
    函数(名称){…}
    而不是
    name=>readFile(名称)
    ?在
    readFile
    内部,我有另一个回调,它是否也会等待所有内部回调?否
    Promisify
    函数仅包装已作为参数传递且带有promise的函数。但
    readFIle
    本身具有回调。如何考虑?还有,我应该把<代码>如果(Err)扔错;
    element.obj=JSON.parse(数据)?但是
    readFIle
    本身有一个回调。如何去考虑?当它被允诺时,它会返回承诺。我们可以使用promise.then(或wait)而不是提供回调作为参数
    element.obj=JSON.parse(数据)?您可以删除try/catch块,然后Promise.all将抛出错误。关于元素-你可以在承诺之后在循环中完成。allI变得非常困惑。
    
    const fileNames = [...] // array with file names
    // this create an array of promises, each of them read one file and returns the file content in JSON
    const promises = fileNames.map(function (singleFileName) {
        return readFile(singleFileName)
        .then(function (singleFileContent) {
           return JSON.parse(singleFileContent)
        })
    })
    
    // promise all resolves (calls callback in 'then') all of promises in array are resolved and pass to then callback array with result of each promise
    Promise.all(promises)
      .then(function (arrayWithResults) {
        return analyze(arrayWithResults)
      })
      // catch callback calls if one of promises in array rejects with error from the promise - so you can handle e.g. read file error or json parsing error here
      .catch(function (error) {
        //here you can handle any error
        console.log(error)
      })