首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >async.waterfall复制调用

async.waterfall复制调用
EN

Stack Overflow用户
提问于 2014-07-23 20:29:30
回答 2查看 143关注 0票数 0

我有下面的异步代码。

代码语言:javascript
复制
  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

我预计输出会是这样的:

代码语言:javascript
复制
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

相反,我得到的是:

代码语言:javascript
复制
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中也是相同的输出)

EN

回答 2

Stack Overflow用户

发布于 2014-07-23 20:40:48

async库不会复制调用,但是这里的作用域有问题。

当调用第一个函数时,循环中的fileName已经设置为file2,您应该尝试将其包装到另一个函数中,以便获得一个新的作用域,如下所示:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2014-07-23 21:03:18

看起来async.waterfall也是异步的,所以您的循环在瀑布回调之前终止,并且使用相同的fileName调用瀑布2次。

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24910509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档