2017-05-08 159 views
1

我有一个方法是使用evalAsync和我想设置一个最大等待时间来解决承诺,如果等待时间达到最大超时那么承诺将是解决并返回空。有关如何完成此任何想法?

很难找到解决方案,因为每个搜索条件evalasync和超时,“污染”结果$超时。

if (angular.isFunction(this.search)) { 
     this.cancellation = this.$q.defer<void>(); 

     this.$scope.$evalAsync(() => { 
      const searchArgs= { 
       value: this.value, 
       cancellation: this.cancellation.promise 
      }; 

      const result = this.search(args); 
     }); 
    } 
}; 

由于

+2

请张贴您的代码。 – Karim

+0

我建议使用'setTimeout'(不是'$ timeout'来防止一个新的摘要循环,并且在这个$ scope。$ evalAsync'之外拒绝'this._cancellation', –

+0

@AlonEitan你能给出一个这个建议的例子吗? – Javiere

回答

2

docs描述 - “的$evalAsync不保证作为当expression将被执行以”

所以,如果你想解决X毫秒后一个承诺,那么你就可以setTimeout结合起来($timeout,因为我们不希望引发消化周期)。

这是我的建议,我只会告诉你基本逻辑,因为我不确定我是否正确理解你的问题,所以请让我知道,以便我可以更改我的答案或删除它,如果它根本没有任何帮助:

var deferred = $q.defer(); 

// Save the timeout ID so we can know what to do with our promise 
var timeout = setTimeout(function() { 
    // Clear the timeout ID and reject the promise after 3 seconds 
    timeout = null; 
    deferred.reject(); 
}, 3000); 

$scope.$evalAsync(function() { 
    if(!timeout) { 
     // Too late, the promise was rejected inside 'setTimeout' 
     return; 
    } 

    // Prevent 'setTimeout' from being executed by clearing its ID 
    clearTimeout(timeout); 

    deferred.resolve({busy: false}); // Of course, you can pass any other value here 
}); 

deferred.promise.then(
    function(data) { console.log('resolved'); }, 
    function() { console.log('rejected'); } 
);