Last active
March 9, 2022 02:24
-
-
Save helabenkhalfallah/4700b08a887c33c33e42ae51c3385f59 to your computer and use it in GitHub Desktop.
Async Http Requests Executor (FiFo) using ES6 Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function httpFiFoRequestsExecutor({ | |
onTaskSuccess, | |
onTaskFail, | |
}) { | |
async function* execute(taskInfos, props) { | |
const { | |
taskIdentifier, | |
taskFn | |
} = taskInfos || {}; | |
try { | |
const result = await taskFn(props); | |
if (onTaskSuccess) { | |
onTaskSuccess( | |
taskIdentifier, | |
result[result.length - 1], | |
result | |
); | |
} | |
const nextTask = yield result; // waiting for the next task | |
yield* execute(nextTask, result); // restart from the begin : recursive call | |
} catch (reason) { | |
if (onTaskFail) { | |
onTaskFail(taskIdentifier, reason); | |
} | |
const nextTask = yield reason; // waiting for the next task | |
yield* execute(nextTask, props); // restart from the begin : recursive call | |
} | |
} | |
// Initiate the async generator | |
// and move the cursor to the first yield. | |
const iterator = execute({ | |
taskIdentifier: null, | |
taskFn: () => [], | |
}, []); | |
iterator.next(); | |
const executeTask = (taskIdentifier, taskFn) => iterator.next({ | |
taskIdentifier, | |
taskFn, | |
}); | |
return { | |
executeTask, | |
cancel: () => iterator.return() | |
}; | |
} | |
const httpRequestsExecutor = httpFiFoRequestsExecutor({ | |
onTaskSuccess: (requestId, requestResponse, responsesStack) => { | |
console.log('onTaskSuccess requestId : ', requestId); | |
console.log('onTaskSuccess requestResponse : ', requestResponse); | |
console.log('onTaskSuccess responsesStack : ', responsesStack); | |
}, | |
onTaskFail: (requestId, requestError) => { | |
console.log('onTaskFail requestId : ', requestId); | |
console.log('onTaskFail requestError : ', requestError.message); | |
}, | |
}); | |
httpRequestsExecutor.executeTask('1', celebrities => Promise.resolve([...celebrities, 'Albert Einsten'])); | |
httpRequestsExecutor.executeTask('2', celebrities => Promise.resolve([...celebrities, 'Nicolas Tesla'])); | |
// asyncHttpFifoExecutor.cancel(); | |
httpRequestsExecutor.executeTask('3', null); | |
httpRequestsExecutor.executeTask('4', celebrities => Promise.resolve([...celebrities, 'Marie Curie'])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment