user2687153
user2687153

Reputation: 447

Wait for an asynchronous method inside a synchronous method?

Here is the situation :

I have 2 JS functions, and I need to wait these 2 methods to do other things.
So I've written :

$.when(foo1(), foo2()).done(function () {
    //do something
});

This works well.

However, in some cases foo2() must load a partial view in my DOM :

function foo2() {
    $("#bar").load('/controller/action')
}

It seems that the code inside the .done callback is executed at the end of foo1() and foo2() whereas the partial view is not fully loaded.

How can I say to foo2() to wait for the end of the partial view loading, before to say "Ok I finished my job, you can continue" ?

Upvotes: 1

Views: 45

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Unfortunately load() doesn't return a promise or deferred object. Instead, to make this work you could manually return a deferred object from foo2() which you resolve after the load() completes. Something like this:

function foo2() {
  var deferred = $.Deferred()
  $("#bar").load('/controller/action', function() {
    deferred.resolve();
  });
  return deferred;
}

Upvotes: 3

Related Questions