2

I have to execute a callback function after all the asynchronous functions finishes execution.
For that I have created an array, containing asynchronous functions:

var funcs = [];
var requests = [];

In which I have pushed some ajax functions.

This is my solution which is not working:

for(i = 0; i < functions.length; i++){
  var f = functions[i](); //calling each ajax functions
  requests.push(f);
}    
$.when.apply(null, requests).done(function(){
    console.log("Hello");
});

Now functions are executing asynchronously, but the callback functions gets called before the functions execution finishes.

One of the example of ajax function I pushed :

functions.push(function () {
  return $.ajax({
    url: "some url",
    success: function(){
    console.log("Finished execution");
  }
});
Rohini Choudhary
  • 2,423
  • 2
  • 21
  • 31
  • 4
    You should relay the promise returned by `$.ajax()` to your caller. In other words, `return $.ajax({ /* ... */ });`. Also note that the code in your question contains a syntax error. – Frédéric Hamidi Jan 29 '15 at 09:11
  • 1. The code has errors. 2. Try adding a `console.log( "Function called" );` before `$.ajax` in the function. – sarveshseri Jan 29 '15 at 09:11
  • 1
    The edit has fixed the fact you're not calling the functions, but you still need to do as @FrédéricHamidi suggests and return the result of `$.ajax` in your example function. – James Thorpe Jan 29 '15 at 09:21
  • Now the functions running, but callback function gets called first, instead of at last, before all the functions finishes execution. – Rohini Choudhary Jan 29 '15 at 09:28
  • @rohinichaudhary please add the new code to your question (without removing the old code) so that we can see what you have now. – Alnitak Jan 29 '15 at 09:30
  • You need to do `return $.ajax(/*...` in your example function, rather than just `$.ajax(/*....`, as @FrédéricHamidi mentioned in the beginning. – James Thorpe Jan 29 '15 at 09:32
  • I have not removed anything, just added little bit of code. The current code above works for asynchronous call but still `.done` method executes before they finishes – Rohini Choudhary Jan 29 '15 at 09:35
  • "Now functions are executing asynchronously" - No, think about it! The functions are executed *synchronously*. Each function *should* return a promise - then it will work. – Roamer-1888 Jan 29 '15 at 09:42

1 Answers1

1

Your anonymous function has no return so its effective return value is undefined.

So, first you need to fix your anonymous function to include a return:

functions.push(function() {
     return $.ajax(...);
});

You can also make a cleaner implementation of your invocation loop:

var requests = functions.map(function(f) {
    return f();
});

$.when.apply($, requests).done(callb);
Alnitak
  • 334,560
  • 70
  • 407
  • 495