mik*_*ana 4 javascript asynchronous node.js node-async async.js
我正在使用caolan的'async'模块打开一个文件名数组(在本例中是模板文件名).
根据文档,我正在使用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')
}
}
)
Run Code Online (Sandbox Code Playgroud)
输出如下:
one
two
three
woo one found
woo two found
woo three found
Run Code Online (Sandbox Code Playgroud)
即,似乎最终的回调没有解雇.我需要做什么才能使最终的回调发生火灾?
mik*_*ana 10
正在所有项目上运行的函数必须进行回调,并将其结果传递给回调.请参阅下文(我还将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')
}
})
Run Code Online (Sandbox Code Playgroud)
返回:
one
two
three
woo one found
woo two found
woo three found
YAAAAAAY
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6825 次 |
最近记录: |