2017-05-08 183 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'); } 
);