jQuery $.wait() for *all* deferred's to be rejected?

前端 未结 2 1539
谎友^
谎友^ 2021-01-14 15:55

jQuery has a nice feature of its Deferred API, $.wait() for working with multiple Deferreds / Promises. It returns when:<

2条回答
  •  攒了一身酷
    2021-01-14 16:23

    i had the same problem lately: I think that occurs because $.when is more of a Promise.all implementation.

    I wasn't able to find a Promise.allSettled alternative in the jQuery documentation and across the web so here's my attempt to get it:

    const deferredsAllSettled = deferreds => {
        const settlements = [];
    
        deferreds.forEach(deferred => {
            const settlement = jQuery.Deferred();
    
            deferred.always(settlement.resolve);
    
            settlements.push(settlement);
        });
    
        const returnedDeferred = $.Deferred();
    
        jQuery.when
            .apply(jQuery, settlements)
            .then(() =>
                returnedDeferred.resolve(
                    deferreds.map(deferred => deferred.promise())
                )
            );
    
        return returnedDeferred.promise();
    };
    

    NOTE: I've written that for a utils file so the Promise.allSettled one-only iterable parameter signature was ok for me, if you want to write it in the $.when spirit (passing and getting the $.Deferreds as separate arguments) you'll have to write a little more...

提交回复
热议问题