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

后端 未结 2 403
时光说笑
时光说笑 2021-01-16 19:06

With jQuery I know that I can use $.when() to wait for all of multipe Deferreds to be resolved. (Or for the first one to be rejected.)

2条回答
  •  礼貌的吻别
    2021-01-16 20:02

    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);
    });
    

提交回复
热议问题