异步.瀑布重复调用
async.waterfall duplicates calls
我有以下异步代码:
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
相关文章:
- 如何避免在angular上多次调用方法;s ng重复
- 避免在来自HTML的Scala.js调用中重复包名称
- 我有可能防止黑客使用网络控制台用JavaScript重复调用upvote(AJAX)函数吗
- setTimeout()在忽略间隔的情况下重复调用函数
- 重复调用的同一函数会重置setTimeout内部函数
- Javascript中什么更快?循环或重复的函数调用
- PHP 重复函数调用,最佳实践
- 防止客户端滥用/欺骗奖励用户的重复 Ajax 调用
- ng重复调用控制器功能的次数太多
- 重复“;function(){}.调用(this)"在Uglified JS中
- nodejs或expressjs在没有返回响应的情况下重复调用路由
- 如何在重复满足条件时调用一次辅助函数
- 可以't在对jQueryLite的CSS调用中设置重复属性
- 有史以来最奇怪的函数重复调用
- 角度ng重复支持从0到n重复,而不调用控制器
- 如何在AngularJS中从RT API调用中使电影总标题不重复
- ng中的Angularjs函数重复调用过多次
- 创建不会中断上一次调用的重复动画
- 如何从对象中选择一个随机属性,而不会在多次调用后重复
- Javascript, Twitch API调用,重复图像/空返回