【问题标题】:Using async module to fire a callback once all files are read读取所有文件后,使用异步模块触发回调
【发布时间】:2012-03-17 06:29:33
【问题描述】:

我正在使用caolan's 'async' module 打开一个文件名数组(在本例中为模板文件名)。

根据文档,我使用的是async.forEach(),因此我可以在所有操作完成后触发回调。

一个简单的测试用例是:

var async = require('async')
var fs = require('fs')

file_names = ['one','two','three'] // all these files actually exist

async.forEach(file_names, 
    function(file_name) {
        console.log(file_name)
        fs.readFile(file_name, function(error, data) {
            if ( error) {   
                console.log('oh no file missing')   
                return error
            } else {
                console.log('woo '+file_name+' found')
            }       
        })
    }, function(error) {
        if ( error) {   
            console.log('oh no errors!')
        } else {
            console.log('YAAAAAAY')
        }
    }
)

输出如下:

one
two
three
woo one found
woo two found
woo three found

也就是说,最终回调似乎没有触发。我需要做什么才能使最终的回调触发?

【问题讨论】:

    标签: javascript node.js asynchronous async.js node-async


    【解决方案1】:

    在所有项目上运行的函数必须接受回调,并将其结果传递给回调。见下文(我还分离了文件名以提高可读性):

    var async = require('async')
    var fs = require('fs')
    
    var fileNames= ['one','two','three']
    
    
    // This callback was missing in the question.
    var readAFile = function(fileName, callback) {
        console.log(fileName)
        fs.readFile(fileName, function(error, data) {
            if ( error) {   
                console.log('oh no file missing')   
                return callback(error)
            } else {
                console.log('woo '+fileName+' found')
                return callback()
            }       
        })
    }
    
    async.forEach(fileNames, readAFile, function(error) {
        if ( error) {   
            console.log('oh no errors!')
        } else {
            console.log('YAAAAAAY')
        }
    })
    

    返回:

    one
    two
    three
    woo one found
    woo two found
    woo three found
    YAAAAAAY
    

    【讨论】:

      【解决方案2】:

      在我看来,这是最好的方法。结果参数将有一个包含文件数据的字符串数组,所有文件将被并行读取。

      var async = require('async')
          fs    = require('fs');
      
      async.map(['one','two','three'], function(fname,cb) {
        fs.readFile(fname, {encoding:'utf8'}, cb);
      }, function(err,results) {
        console.log(err ? err : results);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-12
        • 1970-01-01
        • 2015-11-21
        • 2015-05-29
        • 1970-01-01
        • 2013-09-29
        • 2017-01-13
        • 2020-10-11
        相关资源
        最近更新 更多