异步.瀑布重复调用

async.waterfall duplicates calls

本文关键字:调用 布重复 异步      更新时间:2023-09-26

我有以下异步代码:

  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

我不明白为什么会这样。(这是一个咖啡手稿,没有问题。在JS中也是相同的输出)

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

看来async。瀑布也是异步的,所以你的循环在瀑布回调之前终止,瀑布被调用2次,使用相同的fileName。

但在这里,瀑布是无用的,你可以简单地使用readFileSync同步。

http://nodejs.org/api/fs.html fs_fs_readfilesync_filename_options