使用 $q.race 为 $q promise 添加超时

Using $q.race to add a timeout to a $q promise

我有一个返回 $q.defer().promise 的函数。 在其他函数中,我调用此函数并根据此承诺执行 then

我试图找出如何在这个承诺上超时以拒绝他,但我唯一找到的是如何在 $http 函数上超时。

提前致谢,对不起我的英文。

要创建一个可以从另一个承诺超时的承诺,请使用 $q.race

var dataPromise = service.getData();

var timeoutPromise = $timeout(function(){}, 2000);

timeoutPromise = timeoutPromise
  .then(function() {
    return $q.reject("Timeout");
});

var dataOrTimeoutPromise = $q.race([dataPromise, timeoutPromise]);

上面的示例创建了一个承诺,该承诺将在 2000 毫秒后用数据解析或以 "Timeout" 的原因拒绝,以先到者为准。

有关详细信息,请参阅 AngularJS $q Service API Reference ($q.race)


This is looks good but I use angular 1.5.7 and this function added in angular 1.5.8. Promise.race will do the same or should I implement this method like here $q.race() in old angular versions.

如果您使用 Promise.race,请务必将其转换为带有 $q.when 的 $q 承诺:

var dataOrTimeoutPromise = $q.race([dataPromise, timeoutPromise]);

//OR

var dataOrTimeoutPromise = $q.when(Promise.race([dataPromise, timeoutPromise]));

AngularJS 通过提供自己的事件处理循环来修改正常的 JavaScript 流程。这将 JavaScript 分为经典和 AngularJS 执行上下文。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性 监视等。使用 $q.when 将 ES6 承诺引入AngularJS 执行上下文。

来自文档:

$q.when

Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.

— AngularJS $q Service API Reference (q.when)