$ Q承诺不解决 [英] $q promise not resolving

查看:306
本文介绍了$ Q承诺不解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想不通这是为什么不解决,任何想法? 解决这个可以打印,但它永远不会使它返回到。然后承诺的分辨率。

  VAR承诺= wait()方法;
promise.then(功能(结果){
    的console.log(等待返回 - +结果);
});功能等待(){
    变种推迟= $ q.defer();
    如果(忙){
        的setTimeout(函数(){
            等待();
        },500);
    }其他{
        的console.log(解决此);
        deferred.resolve(等待已经结束了。);
    }
返回deferred.promise;
};


解决方案

下面是如何可以代替完成:

  VAR承诺= wait()方法;
promise.then(功能(结果){
    的console.log(等待返回 - +结果);
});功能等待(){
  变种推迟= $ q.defer();
  (函数_wait(){
    如果(忙){
      的setTimeout(_wait,500);
    }其他{
      的console.log(解决此);
      deferred.resolve(等待已经结束了。);
    }
  })();
  返回deferred.promise;
};

关键区别在于,将只有一个延迟,创建一个包装函数返回。这种延迟将 _wait 函数来最终解决。

在你的情况,以后每次(递归)等待()调用创建一个不同的延迟对象。其中一个对象将最终解决,正确的 - 但是,这将是由第一个返回的同一个对象等待()调用只有当将在这一刻假的。显然,大多数时候也不会

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; 
}; 

解决方案

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.

这篇关于$ Q承诺不解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆