Skip to content Skip to sidebar Skip to footer

$q Promise Not Resolving

I can't figure out why this isn't resolving, any ideas? 'resolve this' does print, but it never makes it back to the resolution of the promise in .then. var promise = wait(); pro

Solution 1:

Here's how it can be done instead:

var promise = wait(); 
promise.then(function(result){
    console.log("wait returned - " + result); 
}); 

functionwait(){
  var deferred = $q.defer();
  (function_wait() {
    if (busy) { 
      setTimeout(_wait, 500);
    } else {
      console.log("resolve this");
      deferred.resolve("Wait is over."); 
    }
  })();
  return deferred.promise;
};

The key difference is that there will be only one deferred, created and returned by a 'wrapper' function. This deferred will be eventually resolved by _wait function.

In your case, each subsequent (recursive) wait() call creates a different deferred object. One of these objects will be eventually resolved, right - but that will be the same object as returned by the first wait() call only if busy will be false at this moment. Apparently, most of the time it won't.

Solution 2:

Each time you call wait, it makes a new promise. The calls to wait inside your setTimeout function do nothing to the first promise created. Try this instead:

var promise = wait(); 
promise.then(function(result){
    console.log("wait returned - " + result); 
}); 

functionwait(){
    var deferred = $q.defer();
    var timer = setInterval(function() {
        if(!busy) {
            clearInterval(timer);
            console.log("resolve this");
            deferred.resolve("Wait is over."); 
        }
    }, 500);
    return deferred.promise; 
};

Also, depending on how the rest of your program is structured, it may be a good idea to resolve the promise as soon asbusy becomes true; then you don't have to wait as long.

Post a Comment for "$q Promise Not Resolving"