在我的AjaxPromiseService.js
工厂中,我一直试图将超时机制纳入承诺调用(通常为$ http.get/post调用远程服务)。我目前的做法是在$timeout
事件和实际承诺呼叫之间建立一个竞赛。示例代码如下(以AngularJS代码从我AjaxPromiseService.js
厂):also available in this plnkrAngularJS:超时承诺电话
var timeoutObj = {"isTimeout": true};
function timeoutPromise(deferredObj) {
$timeout(function() {
console.log("promise timeout");
deferredObj.resolve(timeoutObj);
}, timeoutLimit); // timeoutLimit is in milisecond
}
//promise calls (e.g. $http.get())
function getDummyData(milisec) {
var data = {"data" : "dummy data from ajax!"};
var deferred = $q.defer();
timeoutPromise(deferred); //start the race to see who resolves first
//use $timeout to mimick an AJAX call
$timeout(function() {
deferred.resolve(data);
$timeout.cancel(timeoutPromise(deferred)); //not working, how to cancel the race here?
}, milisec); //
return deferred.promise;
} //getDummyData
这似乎工作,如果getDummyData()
未在规定的时间内解决,timeoutPromise()
将返回有用的标志,所以我可以让AJAX调用优雅地失败。 timeoutPromise()
和getDummyData()
将最终按顺序排序,但是,我想取消timeoutPromise()
如果getDummyData()
首先被解决。我想知道如何做到这一点?
我需要返回prommise,而不是解决数据。谢谢 – TonyGW
'return $ http()。then()'返回一个承诺...我不确定你在问什么 - 否则 - 承诺什么? –
因此,您不需要在$ http()中包装$ q.defer()来返回承诺? – TonyGW