Skip to content

Instantly share code, notes, and snippets.

@artalar
Created November 8, 2018 08:32
Show Gist options
  • Save artalar/e6e8b401448ecbac61546e9a2d0ab24f to your computer and use it in GitHub Desktop.
Save artalar/e6e8b401448ecbac61546e9a2d0ab24f to your computer and use it in GitHub Desktop.
const createConcurrentRequest = () => {
let lastReq;
return async (request, ...params) => {
let myReq = (lastReq = request(...params));
let response = null;
let error = null;
do {
try {
error = null;
response = await (myReq = lastReq);
} catch (e) {
error = e;
}
} while (myReq !== lastReq);
if (error) throw error;
return response;
};
};
// api.example.js
export class ManualError extends Error {}
const concurrentFetchData = createConcurrentRequest();
export const fetchData = payload => concurrentFetchData(fetch, payload);
export const fetchDataCancel = () => concurrentFetchData(() => { throw new ManualError() });
// workflow.example.js
handleFetch = async payload => {
try {
this.onUpdate(await fetchData(payload))
} catch (error) {
if (error instanceof ManualError) this.reset()
else this.onError(error)
}
}
handleCancel = () => fetchDataCancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment