How to use $q's constructor syntax with Angular $http's config.timeout?

不羁的心 提交于 2019-12-12 02:17:01

问题


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.")


回答1:


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.



来源:https://stackoverflow.com/questions/36165800/how-to-use-qs-constructor-syntax-with-angular-https-config-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!