Skip to content

Instantly share code, notes, and snippets.

@LordZardeck
Created August 23, 2022 17:52
Show Gist options
  • Save LordZardeck/c7aa13665435098977e5b65dc26aabb1 to your computer and use it in GitHub Desktop.
Save LordZardeck/c7aa13665435098977e5b65dc26aabb1 to your computer and use it in GitHub Desktop.
Sequential Promises using Map Reduce
[1, 2, 3, 4, 5]
.reduce(
sequentialPromise(element => new Promise(resolve =>
setTimeout(
() => {
console.log(`Handled ${element}`);
resolve(element * Math.floor(Math.random() * 100));
},
Math.random() * 1000
)
)),
Promise.resolve()
)
.then(result => console.log(`Result: ${result}`));
function sequentialPromise(callback) {
return (prevPromise, currentElement, index) => {
return prevPromise.then(results =>
callback(currentElement, index)
.then(result => [...(results || []), result])
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment