gpt4 book ai didi

javascript - async.waterfall 重复调用

转载 作者:行者123 更新时间:2023-12-03 12:12:17 25 4
gpt4 key购买 nike

我有以下异步代码。

  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 中也有相同的输出)

最佳答案

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

关于javascript - async.waterfall 重复调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24910509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com