本文介绍了如何在Angular $ http的config.timeout中使用$ q的构造函数语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

既然现在已经正式指定了Promise,那么如何在下面的代码段中转换$q.defer() promise创建以改为使用$q(function (resolve, reject) {})构造函数语法?

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
  });
}

(来自 $ http docs 的Fyi:timeout是"...以毫秒为单位,或者承诺解决后应中止请求."

(Fyi from $http docs: timeout is "… in milliseconds, or promise that should abort the request when resolved.")

推荐答案

我会这样做:

var canceller = null;
function getThing(id) {
  if (canceller) canceller();
  return Promise.resolve($http.get('/api/things/' + id, {
    timeout: new Promise(function(resolve) {
      canceller = resolve;
    })
  }));
}

我将假设您从未使用过canceller.reject,因此您可以保留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的构造函数语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 10:41