javascript 使用 jQuery 在多个 Promise 并行后等待完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20479378/
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-27 18:35:21  来源:igfitidea点击:

Wait for completion after multiple promises in parallel using jQuery

javascriptjqueryasynchronouscallbackdeferred

提问by crishushu

I want to queue multiple asynchronous ajax requests using deferred/promise implementation of jquery:

我想使用 jquery 的延迟/承诺实现对多个异步 ajax 请求进行排队:

function doSomething() {
    console.log('doSomething')};

function makeMultiAjaxRequests1() {
    console.log('makeMultiAjaxRequests1')};

function makeMultiAjaxRequests2() {
    console.log('makeMultiAjaxRequests2')};

var step1 = function () { 
    var promise = new $.Deferred().promise();   
    makeMultiAjaxRequests1(); 
    return promise; }

var step2 = function () {
    var promise = new $.Deferred().promise();
    makeMultiAjaxRequests2();
    return promise; } 

step1()
   .then(step2())
   .done(doSomething());

$.when(step1(), 
       step2())
   .done(function () {
    doSomething();
});

Here is the fiddle link. So my question is:

这是小提琴链接。所以我的问题是:

In the pattern where step1 and step2 are executed in parallel, the code does not reach the last handler function. Why?

在 step1 和 step2 并行执行的模式中,代码没有到达最后一个处理函数。为什么?

回答by Daiwei

You need to resolve the deferredobj in step1 and step2

你需要deferred在step1和step2中解决obj

Try this

试试这个

function doSomething() {
    console.log('doSomething')};

function makeMultiAjaxRequests1(deferred) {
    console.log('makeMultiAjaxRequests1')
    deferred.resolve()};

function makeMultiAjaxRequests2(deferred) {
    console.log('makeMultiAjaxRequests2')
    deferred.resolve()};

var step1 = function () { 
    var deferred = new $.Deferred();   
    makeMultiAjaxRequests1(deferred); 
    return deferred; }

var step2 = function () {
    var deferred = new $.Deferred();
    makeMultiAjaxRequests2(deferred);
    return deferred; } 

step1().then(step2).done(doSomething);

$.when(step1(), step2()).done(function () {
    doSomething();
});

回答by mraxus

@Daiwei gives a good answer.

@Daiwei 给出了很好的答案。

A common gist to be referred to is https://gist.github.com/sergio-fry/3917217by sergio-fry.

要参考的常见要点是sergio-fry 的https://gist.github.com/sergio-fry/3917217

Should you want to have a more dynamic approach where you don't know beforehand how many arguments you are running parallel, here is a good example extension of JQuery (1.10+):

如果您想要一种更动态的方法,而您事先不知道并行运行了多少个参数,这里是 JQuery (1.10+) 的一个很好的扩展示例:

$.whenAll = function (deferreds) {
    function isPromise(fn) {
        return fn && typeof fn.then === 'function' &&
            String($.Deferred().then) === String(fn.then);
    }
    var d = $.Deferred(),
        keys = Object.keys(deferreds),
        args = keys.map(function (k) {
            return $.Deferred(function (d) {
                var fn = deferreds[k];

                (isPromise(fn) ? fn : $.Deferred(fn))
                    .done(d.resolve)
                    .fail(function (err) { d.reject(err, k); })
                ;
            });
        });

    $.when.apply(this, args)
        .done(function () {
            var resObj = {},
                resArgs = Array.prototype.slice.call(arguments);
            resArgs.forEach(function (v, i) { resObj[keys[i]] = v; });
            d.resolve(resObj);
        })
        .fail(d.reject);

    return d;
};

See the code in action with a dynamic live example:

使用动态示例查看正在运行的代码:

http://jsbin.com/nuxuciwabu/edit?js,console

http://jsbin.com/nuxuciwabu/edit?js,console

回答by Ryley

It does reach your donefunction if you give it a URL it can actually reach (in the case of jsfiddle, that would be say /echo/html/: http://jsfiddle.net/LnaPt/2/

done如果你给它一个它可以实际到达的 URL,它确实可以到达你的功能(在 jsfiddle 的情况下,那就是/echo/html/http: //jsfiddle.net/LnaPt/2/

Basically, you just need to do this:

基本上,你只需要这样做:

var promise = $.ajax({
    type: "GET",
    url: "/echo/html/",   //<-- instead of google     
}).promise();