1

How to use dynamic deferred's inside $.when? Got one function ajaxFunction which returns deferred promise.

function ajaxFunction(image){
    var dfd = $.Deferred();
    //Ajax of image
    return dfd.promise();
}

calling this ajaxFunction based on dynamic condition like

var defs = {};
var someQuerySelector = document.querySelectorAll('image');
for (var i = 0; i < someQuerySelector.length; i++) {
    defs[d + 'i'] = ajaxFunction(someQuerySelector[i]);
}

Now I want to use these into $.when() how to use defs dynamic keys inside like $.when(defs['d1'],defs['d2']). How to use dynamic variables into this. Any change in approach or help will be highly appreciated.

1 Answer 1

2

If you change defs to an array you can apply() it to $.when, like this:

var defs = [];
var someQuerySelector = document.querySelectorAll('image');
for (var i = 0; i < someQuerySelector.length; i++){
  defs.push(ajaxFunction(someQuerySelector[i]));
}

$.when.apply(this, defs).done(function() {
    // all complete, do something...
});

Or purely in jQuery:

var defs = $('image').map(function() {
    return ajaxFunction(this);
});

$.when.apply(this, defs).done(function() {
    // all complete, do something...
});

The above is assuming that you change image to a valid selector, and that you're providing some parameters to your ajaxFunction(), otherwise repeatedly calling it the same way N times is pretty redundant.

Sign up to request clarification or add additional context in comments.

2 Comments

yes I am using image as parameter. Updated the question also
$.when.apply(null, defs) this worked for me :) Thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.