【问题标题】:async.eachSeries callback calling multiple timesasync.eachSeries 回调多次调用
【发布时间】:2014-03-01 03:26:53
【问题描述】:

在这个函数中:

function method2(friends, callback) {
    //friends is an array of objects
    var ids = _.pluck(friends, 'id'),
        arrays = cut(ids, 24),
        //cut() splits array into smaller arrays of given length 
        code = require('fs').readFileSync('...').toString();
    var imp,j;
    async.eachSeries(arrays, function(i, cb1) {
        ...
        vk.request('execute', {code:code}, function(err, resp, body) {
            //vk.request passes its callback to node-request module
            //at this point, err is null, and body.error is undefined
            if(err || body.error) return cb1(err || body.error);
            var arr = body.response;
            for(var e in arr) {
                if(!arr[e]) return cb1();
                async.eachSeries(arr[e], function(i, cb) {
                    ...
                    cb();
                }, cb1);
            }
        })
    }, callback);
}

function 只被调用一次,但是 async 多次调用 callback 而不提供任何参数。我看不出任何原因。那么这段代码有什么问题呢?

【问题讨论】:

  • 不知道我明白了,你真的有带回调的异步函数,还是你错误地在常规数组上使用了 async.eachSeries?
  • 请修正您的代码缩进。
  • @adeneo: arrays 变量是一个常规数组
  • 那你为什么要使用异步?
  • @adeneo:异步迭代这个数组

标签: javascript node.js node-async


【解决方案1】:

我认为你的问题在这里:

for(var e in arr) {
    // ...
    async.eachSeries(/* ... */, cb1);

您多次调用cb1,这导致最外面的async.eachSeries 继续多次,因此最终的callback 被多次调用。

解决方案:使用async.each 而不是简单的for 循环来生成多个并发的内部async.eachSeries 循环(如果这确实是您想要的)。这是内嵌异步循环的方式:

async.eachSeries(/* ... */, function(/* ... */, cb1) {
  // this body runs once at a time
  async.each(/* ... */, function(/* ... */, cb2) {
    // this body runs multiple times 'concurrently'
    async.eachSeries(/* ... */, function(/* ... */, cb3) {
       // this body runs sequentially,
       // but multiple sequential runs can happen at once
       cb3(/* ... */);
    }, cb2);
  }, cb1);
}, callback);

题外话:不建议使用readFileSync,除非在应用程序启动时(当且仅当使用require 是安全的,使用readFileSync 也是安全的)。由于您使用的是 async 调用,我必须假设这是一个事务函数,因此您应该通过回调将其更改为 fs.readFile

第二个好处:当然,太过分了,这种嵌套会变成一团糟。 There are ways to combat this using functional programming techniques.

【讨论】:

    猜你喜欢
    • 2018-02-09
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2015-12-31
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多