本文介绍了将多个jQuery Deferred对象合并为一个新的Deferred对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码: http://jsbin.com/lizami/edit?js,console

也将代码粘贴到这里:

var aaa = $.Deferred();

var bbb = function(data){

    console.log(data);

    var dfd = $.Deferred();
    setTimeout(function(){
        dfd.resolve("bbb is done");
    }, 1000);
    return dfd.promise();
};

var ccc = function(data){
    console.log(data);

    var dfd = $.Deferred();
    setTimeout(function(){
        dfd.resolve("ccc is done");
    }, 1000);
    return dfd.promise();
};

var ddd = function(data){
    console.log(data);

    return data;
};



aaa.then([bbb,ccc]).then(ddd);
aaa.resolve("aaa is done");

我要启动的两个新的递延时间:bbbccc,当aaa被解析时.并且同时解析了bbbccc时.用解析后的数据bbbccc调用ddd.

What I want is to start two new deferred: bbb and ccc when aaa is resolved. And when both bbb and ccc are resolved. call ddd with the resolved data of bbb and ccc.

有可能吗? jsbin无法正常工作

Is it possible? The jsbin doesn't work

推荐答案

在jQuery中,您可以使用$.when()将多个promise合并为一个.

In jQuery, you can use $.when() to combine multiple promises into one.

aaa.then(function() {
    return $.when(bbb(), ccc());
}).then(ddd);

这将等待aaa解析,然后将同时运行bbb()ccc(),当它们都解析时,它将调用ddd().

This will wait for aaa to resolve, then it will run both bbb() and ccc() and when they both resolve, it will then call ddd().

正在运行的演示: http://jsfiddle.net/jfriend00/2f7btsq7/

这篇关于将多个jQuery Deferred对象合并为一个新的Deferred对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 05:20