0

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

thatmarvin
  • 2,800
  • 4
  • 22
  • 31

1 Answers1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • $http.get() returns a promise, so I don't think it needs the Promise.resolve() wrap? – thatmarvin Mar 23 '16 at 14:52
  • @thatmarvin: It doesn't return one of those shiny new officially specced `Promise`s, but an old boring AngularJs-promise :-) If you want to use Angular promises (and `$q` instead of `new Promise`) then you can omit it of course. – Bergi Mar 23 '16 at 14:56
  • gotcha, accepted. very obvious now that i see it, thanks! – thatmarvin Mar 23 '16 at 15:08