【问题标题】:async.waterfall duplicates calls [duplicate]async.waterfall 重复调用 [重复]
【发布时间】:2014-09-14 15:20:04
【问题描述】:

我有以下异步代码。

  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 中也是一样的输出)

【问题讨论】:

    标签: javascript for-loop asynchronous coffeescript async.js


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      async.waterfall 似乎也是异步的,因此您的循环在瀑布回调之前终止,瀑布被调用 2 次,文件名相同。

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-22
        • 1970-01-01
        • 2019-09-17
        • 2018-11-07
        • 2013-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多