How to cancel a Promise
Although there were a proposal and an alternative implementation, native promises offer no built-in way for cancellation. When you don't need the result by the time it is ready, you need to handle it manually.
For example, there is a select element that fetches some data from a remote server on every change. This solution works only when the fetch is faster than the user:
longFetch(value).then((res) => {
// Show the result...
});
If the user selects A
then B
, the first fetch is no longer relevant; therefore its result should be discarded.
Solution 1
The first idea is to check the selected element and make sure it's the same:
longFetch(value).then((res) => {
if (selectElement.value === value) {
// Show the result...
}
});
But when the user selects A
, then B
, then A
again, two fetches will refresh instead of one. It may or may not be a problem, but might cause a flickering.
Solution 2
A more robust solution is to store the timestamp of the last fetch and check against that. If the timestamps do not match, discard the result.
let lastFetch;
...
const currentTime = new Date().getTime();
lastFetch = currentTime;
longFetch(value).then((res) => {
if (lastFetch === currentTime) {
// Show the result...
}
});