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

6
  • I don't get what your goal is. Your code is fine and working, there's no reason to change anything. Commented Mar 23, 2016 at 0:09
  • "How do I use the promise constructor syntax?" - You don't! Commented Mar 23, 2016 at 0:09
  • no goal. just an academic exercise Commented Mar 23, 2016 at 14:37
  • Note that the native Promise object does not have a "deferred" api. It seems like timeout should be able to accept any then-able object here. Commented Mar 23, 2016 at 14:45
  • Oh wait, now I get it. You don't want to convert the $http.get call, but the $q.defer creation to use the Promise constructor? Commented Mar 23, 2016 at 14:46

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

$http.get() returns a promise, so I don't think it needs the Promise.resolve() wrap?
@thatmarvin: It doesn't return one of those shiny new officially specced Promises, 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.
gotcha, accepted. very obvious now that i see it, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.