Canceling asynchronous actions with Promise.race()
ES6 introduces Promise.race()
, which is absent from the $q
spec in Angular 1. Like Promise.all()
, this static method accepts an iterable collection of promise objects; whichever one resolves or rejects first will become the result of the promise wrapping the collection. This may seem like unusual behavior, but it becomes quite useful when you're building a cancellation behavior into the system.
Note
The code, links, and a live example of this are available at http://ngcookbook.herokuapp.com/4362/ .
Getting ready
Suppose you started with a simple promise that resolves to a value after 3 seconds:
const delayedPromise = new Promise((resolve, reject) => setTimeout(resolve.bind(null, 'foobar'), 3000)) .then(val => console.log(val));
You would like to have the ability to detach a part of your application from waiting for this promise.
How to do it...
A simple solution would be to expose the promise's reject handler and just...