我有下面的异步代码。
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中也是相同的输出)
发布于 2014-07-23 20:40:48
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发布于 2014-07-23 21:03:18
看起来async.waterfall也是异步的,所以您的循环在瀑布回调之前终止,并且使用相同的fileName调用瀑布2次。
但是在这里,瀑布是没有用的,你可以简单地使用同步的readFileSync。
http://nodejs.org/api/fs.html#fs_fs_readfilesync_filename_options
https://stackoverflow.com/questions/24910509
复制相似问题