Jimmy Jimmy - 8 months ago 52
jQuery Question

jquery - $.when() with single deferred and array of deferred

I'm using jquery and have two variables.

trackFeatures - single ajax request, artistRequests - array of ajax requests

I want to do something when both trackFeatures and artistRequests have completed. For just artistRequests, I can do:

$.when.apply($, artistRequests).done(function() { ... }

Is there a way to combine the single request with the array requests? Besides adding the single request to the array or testing them sequentially.


Answer Source

Referring this link and example :

var d1 = $.Deferred();
var d2 = $.Deferred();
$.when( d1, d2 ).done(function ( v1, v2 ) {
    console.log( v1 ); // "Fish"
    console.log( v2 ); // "Pizza"
d1.resolve( "Fish" );
d2.resolve( "Pizza" );

Similarly if you have array of promises like artistRequests = [d1,d2]

You can use spread operator for array like

$.when( ...artistRequests ).done(function ( v1, v2 ) {
    console.log( v1 ); // "Fish"
    console.log( v2 ); // "Pizza"

PS: ...artistRequests split the each value of array in single variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download