我有以下异步代码。
for fileName in sourceFiles
console.log 'dealing with ', fileName
async.waterfall [
(callback) ->
console.log "going to read ", fileName
fs.readFile fileName, (err, content) ->
if err then throw err
callback null, fileName, content
return
(fileName, content, callback) ->
console.log 'length of: ', fileName, ' is: ', content.length
我预计输出会是这样的:
dealing with file1
going to read file1
length of file1 is 10
dealing with file2
going to read file2
length of file 2 is 20
相反,我得到的是:
dealing with file1
dealing with file2
going to read file2
going to read file2 <- note it is the same file repeated
length of file2 is 20
length of file2 is 20
我无法弄清楚为什么会这样。 (这是一个coffeescript没有问题。它在JS中也是相同的输出)
答案 0 :(得分:1)
async
库不会重复调用,但您在此处遇到了一个问题。
当您的第一个函数被调用时,循环中的fileName
已设置为file2
,您应该尝试将其包装到另一个函数中,只是为了获得一个新的作用域,如下所示:
for fileName in sourceFiles
(fileName) ->
console.log 'dealing with ', fileName
async.waterfall [
(callback) ->
console.log "going to read ", fileName
fs.readFile fileName, (err, content) ->
if err then throw err
callback null, fileName, content
return
(fileName, content, callback) ->
console.log 'length of: ', fileName, ' is: ', content.length
答案 1 :(得分:0)
async.waterfall似乎也是异步的,所以在使用相同的fileName调用瀑布回调和瀑布2次之前终止循环。
但是在这里,瀑布是没用的,你可以简单地使用同步的readFileSync。
http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options