$q promise not resolving

断了今生、忘了曾经 提交于 2019-12-12 02:51:13

问题


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(); 
promise.then(function(result){
    console.log("wait returned - " + result); 
}); 

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

回答1:


Here's how it can be done instead:

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

function wait(){
  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.




回答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); 
}); 

function wait(){
    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 as busy becomes true; then you don't have to wait as long.



来源:https://stackoverflow.com/questions/26409778/q-promise-not-resolving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!