使用异步模块触发一个回调,一旦所有文件都读 [英] Using async module to fire a callback once all files are read

查看:154
本文介绍了使用异步模块触发一个回调,一旦所有文件都读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 caolan的异步模块打开文件名的数组(在这种情况下,模板文件名)。

I'm using caolan's 'async' module to open an array of filenames (in this case, template file names).

每文档,我使用 async.forEach(),这样我就可以开火回调一旦所有操作完成。

Per the documentation, I'm using async.forEach(),so I can fire a callback once all operations have completed.

一个简单的测试案例是:

A simple test case is:

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')
        }
    }
)

的输出如下所示:

The output is as follows:

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

即,似乎最终的回调不点火。什么我需要做的,使最终的回调火?

I.e, it seems the final callback isn't firing. What do I need to do to make the final callback fire?

推荐答案

这是正在的所有项目运行必须采取一个回调,其结果传递给回调函数。见下面(我也分开read_a_file以提高可读性):

The function that is being run across all items must take a callback, and pass its results to the callback. See below (I've also separated read_a_file to improve readability):

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

file_names = ['one','two','three']


    // This callback was missing in the question.
var read_a_file = function(file_name, callback) {
    console.log(file_name)
    fs.readFile(file_name, function(error, data) {
        if ( error) {   
            console.log('oh no file missing')   
            return callback(error)
        } else {
            console.log('woo '+file_name+' found')
            return callback()
        }       
    })
}

async.forEach(file_names, read_a_file, 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

这篇关于使用异步模块触发一个回调,一旦所有文件都读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆