Skip to content

Instantly share code, notes, and snippets.

@ptheofan
Last active February 16, 2022 14:39
Show Gist options
  • Save ptheofan/e56dce58c16988ecef912d01cb97d7ed to your computer and use it in GitHub Desktop.
Save ptheofan/e56dce58c16988ecef912d01cb97d7ed to your computer and use it in GitHub Desktop.
Run only the latest promise. Will cancel all the previous ones. Similar to AbortController which couldn't get to work with Axios. This one works.
// Couldn't get the AbortController to work with Axios post so real quick and dirty, similar solution.
// This does NOT abort the request, it just rejects the concurrently previously running promises.
// Can make it abort also though no need to if AbortController works for you.
//
// How to use
// Just wrap your axios call (or any promise in it).
// first parameter is a uid (use some convenient name)
// latestOnly('mySearchCall', ....)
// if you call latestOnly('mySearchCall') before the promise has resolved the previous (still running) promise will
// return error "AbortError"
const cancellable = (promise) => {
let cancelled = false;
const cancel = () => {
cancelled = true;
};
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
value => {
if (cancelled) {
reject(new Error(`AbortError`));
} else {
resolve(value);
}
},
error => {
if (cancelled) {
reject(new Error(`AbortError`));
} else {
reject(error);
}
}
);
});
return {
promise: wrappedPromise,
cancel
};
};
const running = {};
const latestOnly = (uid, promise) => {
if (running[uid]) {
running[uid].cancel();
delete running[uid];
}
running[uid] = cancellable(promise);
return running[uid].promise;
}
export const cancel = (uid) => {
if (running[uid]) {
running[uid].cancel();
delete running[uid];
}
}
export default latestOnly;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment