更新时间:2023-11-20 23:28:22
这是正在的所有项目运行必须采取一个回调,其结果传递给回调函数。见下面(我也分开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