Wait for the first of multiple jQuery Deferreds to be resolved?

安稳与你 提交于 2019-12-01 13:46:59

Based on Kevin B's code, here's an approach that uses a master Deferred object:

var masterDeferred = new $.Deferred(),
    reqOne = $.post("foo.php"),
    reqTwo = $.post("bar.php");

masterDeferred.done(function() {
    // do stuff
});

reqOne.done(function() {
    masterDeferred.resolve();
});
reqTwo.done(function() {
    masterDeferred.resolve();
});

I think I'm right in saying that the simplest form of resolving the masterDeferred would be :

reqOne.done(masterDeferred.resolve);
reqTwo.done(masterDeferred.resolve);

But separate done functions will allow you to branch internally and call .resolve(), .reject(), .resolveWith(...) or .rejectWith(...) as appropriate, together with masterDeferred callbacks of the general form :

masterDeferred.then( doneCallbacks, failCallbacks );

A quick and easy way would be to abort the other request when one of the two finishes, though you could also check the state of the deferred, the syntax of which will depend on your jQuery version which is why I go with abort for now.

function doStuff(data) {
    alert( "Hello World!" );
}
var reqOne = $.post("foo.php"),
reqTwo = $.post("bar.php");

reqOne.done(function(data){
    reqTwo.abort();
    finished = true;
    doStuff(data);
});
reqTwo.done(function(data){
    reqOne.abort();
    finished = true;
    doStuff(data);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!