一旦读取完所有文件,使用asynchronous模块触发callback
我正在使用caolan的“asynchronous”模块来打开一个文件名数组(在本例中是模板文件名)。
根据文档,我使用async.forEach() ,所以我可以在所有操作完成后触发一个callback。
一个简单的testing案例是:
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
也就是说,最后的callback似乎并没有发射。 我需要做什么来做最后的callback火灾?
正在所有项目上运行的函数必须采取callback,并将其结果传递给callback。 见下面(我也分开fileName以提高可读性):
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
这是我认为最好的方法。 结果param将有一个包含文件数据的string数组,并且所有文件将被并行读取。
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); });
- 当使用Node和jsdom到蜘蛛网站时,会导致内存不足
- Mongooseasynchronous调用内循环与asynchronous库
- 我可以在async.js forEach中扩展迭代器的function吗?
- JS:async.each的等价承诺是什么?
- 在Node.js的另一个文件中同步使用返回值
- 当使用node.js async forEachSeries时,是否有等价的语句来“继续”?
- Nodejsasynchronous编程 – 为什么需要“asynchronous”模块? 什么是“回拨地狱”/“厄运金字塔”?
- 每个asynchronous里面的nodejsasynchronous并行
- async.whilst中的callback和错误是什么?