0

I have a function, which declares a variable, uses $.when to perform three ajax requests, modifies the variable inside the .done() method and returns the value:

someFunction = function(){
    var myVar;
    $.when(ajax1(), ajax2(), ajax3()).done(function(){
        myvar = "something";
    });
    return myVar;
}

However, due to its asyncronous nature the return statement is executed first and returns undefined. I confirmed this by adding something before the return statement (for debugging purposes):

setTimeout(function(){
    console.log(myVar);
}, 2000);

After waiting 2 seconds (long enough for all requests and callbacks to finish), it returned the proper value.

So, how should I write this properly in order to make it sync?

Quinteger
  • 133
  • 1
  • 8
  • You cannot make it sync. Don't try. Embrace asynchrony and return a promise (use `then` instead of `done`). – Bergi May 20 '17 at 12:26
  • I think I have to add here, that `someFunction` has to be a function that returns some value, because it redefines another function from a framework I'm using. And I'm yet to figure out how to write this with that thing in mind. – Quinteger May 20 '17 at 13:12
  • As I said, it's just not possible. That framework must support asynchrony. – Bergi May 20 '17 at 17:03

0 Answers0