1

I'd like to use when() to control finishing of multiple AJAX calls such as:

$.when(
    $.ajax( "test.aspx" ),
    $.ajax( "test2.aspx" ),
    ...
).then(...);

Finally I would like to use $.when with results of function calls from a variable array. I don't realize how.

How can we correct the next construction? The problem it's incorrect because we pass an array of Function objects, but not results of function calls.

funcArray = [ 
    function() { return $.ajax( "test.aspx" ) }, 
    function() { return $.ajax( "test2.aspx" ) }
]

if( cond )
{
    funcArray.push( function() { return $.ajax( "test3.aspx" ) } )
}

$.when.apply( null, funcArray ).then(...); // how to correct here and probably somewhere else?
3
  • 1
    Your functions have to return the result of $.ajax(): function() { return $.ajax( "test.aspx" ) } Commented Jan 25, 2014 at 16:32
  • @ComFreek I suppose it's a good correction but it's not the solution, isn't it? Commented Jan 25, 2014 at 16:35
  • $.when accepts promises as its arguments, not functions returning promises. You'll first need to call all your functions, store the returned promises in an array and pass that array to $.when (using apply). Commented Jan 25, 2014 at 16:41

1 Answer 1

2

As Mattias Buelens already said in a comment, the problem is that you pass functions returning promises to $.when – not the actual promises.

You have to iterate the array and return the result of each function call.

There are several ways to do so:

  • [Most stable] Using jQuery's $.map function:

    $.when.apply(null, $.map(funcArray, function (val) {
        return val();
      })
    );
    
  • Using Array.prototype.map():

    $.when.apply(null, funcArray.map(function (val) {
        return val();
      })
    );
    
  • Firefox ≥ 22 also allows a so-called syntax of arrow functions:

    $.when.apply(null, funcArray.map(fun => fun()));
    
Sign up to request clarification or add additional context in comments.

1 Comment

If compatibility is an issue, you can also use $.map(array, func) to replace array.map(func).

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.