javascript - 多次调用 async.eachSeries 回调

标签 javascript node.js node-async

在这个函数中:

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 很多次而不向它提供任何参数。我看不出任何原因。那么这段代码有什么问题呢?

最佳答案

我认为你的问题出在这里:

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.

关于javascript - 多次调用 async.eachSeries 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22098267/

相关文章:

javascript - 从 Javascript 正确导航到 React 路由

javascript - 如何调用在另一个函数中声明的子函数

angularjs - 使用 Angularjs 上传图像

node.js - 异步nodejs中的每个变量范围

node.js - nodejs 中的异步和 Q promise

javascript - Couchdb _design/doc/_update/push 不能作为对象工作

c# - 如何在c#中的文本框之间复制选定的日期

javascript - 如何衡量 React App 随时间推移的首次渲染性能?

javascript - Sinon stub 未替换测试中的功能

javascript - 尝试连续使用 async.forEach 但失败 - Node.js