2014-07-23 64 views
0

我有下面的異步代碼。async.waterfall重複調用

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中的輸出)

回答

1

async庫不會重複調用,但是您在這裏有一個關於作用域的問題。

在循環已經被設置爲file2時,你的第一個函數被調用時,你應該試着來包裝到另一個函數,只是爲了獲得一個新的作用域一起工作,這樣的fileName

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