Return already resolved promise

前端 未结 2 663
無奈伤痛
無奈伤痛 2021-02-01 01:30

I have an existing project that has a lot of asynchronous functions that return promises. I\'m adding some caching so that in some cases the asynchronous functions will complet

2条回答
  •  我在风中等你
    2021-02-01 01:51

    Simply use return $.when(); to return an already resolved promise.

    If you don't pass it any arguments at all, jQuery.when() will return a resolved promise.

    Reference: https://api.jquery.com/jquery.when/


    Notes:

    • This is the same as return $.when(undefined); which leads to the following rather cool trick which avoids any use of arrays and apply.

    If you want to wait for a variable number of promises to complete in parallel then you can use this pattern in a loop:

    var promise;   // Undefined is treated as an initial resolved promise by $.when
    while (insomeloop){
        promise = $.when(promise, newpromise);
    }
    

    then make a final call on completion with:

    promise.then(function(){
        // All done!
    });
    

    e.g.

    var promise;$.when
    var $elements = $('.some-elements');
    $elements.each(function(){
         var $element = $(this).fadeout();
         promise = $.when(promise, $element.promise());
    });
    promise.then(function(){
        // All promises completed!
    });
    

    The downsides are minor:

    • each call to when wraps the previous promise in a new promise. A minor overhead and you no longer need to maintain and evaluate an array of promises.
    • no values can be directly passed through to the final function. As you typically do not want the return values from parallel promises, this is minor.
    • failure of a single promise will abort the final wait early, so you need to ensure all promises will be fulfilled.

提交回复
热议问题