$q Promise Not Resolving
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"