Sometimes, we want to cancel a vanilla ECMAScript 6 Promise chain with JavaScript.
In this article, we’ll look at how to cancel a vanilla ECMAScript 6 Promise chain with JavaScript.
How to cancel a vanilla ECMAScript 6 Promise chain with JavaScript?
To cancel a vanilla ECMAScript 6 Promise chain with JavaScript, we can use the Promise.race
method.
For instance, we write
const actualPromise = new Promise((resolve, reject) => {
setTimeout(resolve, 10000);
});
let cancel;
const cancelPromise = new Promise((resolve, reject) => {
cancel = reject.bind(null, { canceled: true });
});
const cancelablePromise = Object.assign(
Promise.race([actualPromise, cancelPromise]),
{ cancel }
);
to create actualPromise
and the cancelPromise
.
We call Promise.race
with an array with the promise to return a promise with the result of the promise that’s finished first.
And we use that promise to create the cancelablePromise
which merges the cancel
property into the promise returned by race
.
Conclusion
To cancel a vanilla ECMAScript 6 Promise chain with JavaScript, we can use the Promise.race
method.