如何在 Angular $http 的 config.timeout 中使用 $q 的构造函数语法? [英] How to use $q's constructor syntax with Angular $http's config.timeout?
问题描述
由于 Promise
现在是官方指定的,我如何将以下代码段中的 $q.defer()
承诺创建转换为使用 $q(function (resolve, reject) {})
代替构造函数语法?
//取消任何正在进行的 $http 请求,以便只有最近的 $http//回调被调用无功消除器;函数 getThing(id) {if (canceller) canceller.resolve();取消者 = $q.defer();返回 $http.get('/api/things/' + id, {超时:canceler.promise});}
(参考来自 $http docs:timeout
是......以毫秒为单位,或者承诺在解决时应该中止请求.")
我会这样做:
var canceller = null;函数 getThing(id) {如果(取消者)取消者();return Promise.resolve($http.get('/api/things/' + id, {超时:新承诺(功能(解决){取消者=解决;})}));}
我假设您无论如何都不会使用 canceller.reject
,因此您可以保留 resolve
函数本身以便下次调用它.>
Since Promise
is now officially spec-ed and all, how do I convert the $q.defer()
promise creation in the following snippet to use the $q(function (resolve, reject) {})
constructor syntax instead?
// Cancel any ongoing $http request so that only the most recent $http
// callback gets invoked
var canceller;
function getThing(id) {
if (canceller) canceller.resolve();
canceller = $q.defer();
return $http.get('/api/things/' + id, {
timeout: canceller.promise
});
}
(Fyi from $http docs: timeout
is "… in milliseconds, or promise that should abort the request when resolved.")
I'd do it like this:
var canceller = null;
function getThing(id) {
if (canceller) canceller();
return Promise.resolve($http.get('/api/things/' + id, {
timeout: new Promise(function(resolve) {
canceller = resolve;
})
}));
}
I'll assume you'd never have used canceller.reject
anyway, so you can just keep around the resolve
function itself to call it next time.
这篇关于如何在 Angular $http 的 config.timeout 中使用 $q 的构造函数语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!