Javascript - 等待一些异步回调返回?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10291139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:21:27  来源:igfitidea点击:

Javascript - waiting for a number of asynchronous callbacks to return?

javascriptasynchronousunderscore.js

提问by Stefan Kendall

What's the best way/library for handling multiple asynchronous callbacks? Right now, I have something like this:

处理多个异步回调的最佳方式/库是什么?现在,我有这样的事情:

_.each(stuff, function(thing){
   async(thing, callback);
});

I need to execute some code after the callback has been fired for each element in stuff.

我需要在为stuff.

What's the cleanest way to do this? I'm open to using libraries.

什么是最干净的方法来做到这一点?我愿意使用图书馆。

采纳答案by Jamund Ferguson

There is a great library called Async.jsthat helps solve problems like this with many async & flow control helpers. It provides several forEach functions that can help you run callbacks for every item in a an array/object.

有一个叫做Async.js的很棒的库,它通过许多异步和流控制助手帮助解决这样的问题。它提供了几个 forEach 函数,可以帮助您为数组/对象中的每个项目运行回调。

Check out: https://github.com/caolan/async#forEach

查看:https: //github.com/caolan/async#forEach

// will print 1,2,3,4,5,6,7,all done

var arr = [1,2,3,4,5,6,7];

function doSomething(item, done) {
  setTimeout(function() {
    console.log(item);
    done(); // call this when you're done with whatever you're doing
  }, 50);
}

async.forEach(arr, doSomething, function(err) {
    console.log("all done");
});

回答by Jordan Running

Since you're already using Underscore you might look at _.after. It does exactly what you're asking for. From the docs:

由于您已经在使用 Underscore,您可能会查看_.after. 它完全符合您的要求。从文档:

after    _.after(count, function)

Creates a version of the function that will only be run after first being called count times. Useful for grouping asynchronous responses, where you want to be sure that all the async calls have finished, before proceeding.

回答by Peter Lyons

I recommend https://github.com/caolan/asyncfor this. You can use async.parallelto do this.

我为此推荐https://github.com/caolan/async。您可以使用它async.parallel来执行此操作。

function stuffDoer(thing) {
    return function (callback) {
        //Do stuff here with thing
        callback(null, thing);
    }
}

var work = _.map(stuff, stuffDoer)
async.parallel(work, function (error, results) {
    //error will be defined if anything passed an error to the callback
    //results will be an unordered array of whatever return value if any
    //the worker functions passed to the callback
}

回答by skashyap

async.parallel() / async.series should suit your requirement. You can provide with a final callback that gets executed when all the REST calls succeed.

async.parallel() / async.series 应该适合您的要求。您可以提供在所有 REST 调用成功时执行的最终回调。

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);
async.series([
    function(){ ... },
    function(){ ... }
], callback);

回答by Niet the Dark Absol

Have a counter, say async_count. Increase it by one every time you start a request (inside you loop) and have the callback reduce it by one and check if zero has been reached - if so, all the callbacks have returned.

有一个柜台,说async_count。每次启动请求(在循环内部)时将其加一,并让回调将其减一并检查是否已达到零 - 如果是,则所有回调都已返回。

EDIT: Although, if I were the one writing this, I would chain the requests rather than running them in parallel - in other words, I have a queue of requests and have the callback check the queue for the next request to make.

编辑:虽然,如果我是写这篇文章的人,我会链接请求而不是并行运行它们 - 换句话说,我有一个请求队列并让回调检查队列以进行下一个请求。

回答by slebetman

See my response to a similar question:

看我对类似问题的回答:

Coordinating parallel execution in node.js

在 node.js 中协调并行执行

My fork()function maintains the counter internally and automatically.

我的fork()函数在内部和自动维护计数器。