Skip to content

Instantly share code, notes, and snippets.

@DiegoVictor
Created January 26, 2022 22:35
Show Gist options
  • Save DiegoVictor/fa4c6525c5366d77c866f4b5685ff6b7 to your computer and use it in GitHub Desktop.
Save DiegoVictor/fa4c6525c5366d77c866f4b5685ff6b7 to your computer and use it in GitHub Desktop.
Generate promises from an array, run the promises in sequence, starting the next one once the previous finish
async function call(value) {
const label = `Promise ${value}`;
console.time(label);
return new Promise((resolve) => {
setTimeout(() => {
console.timeEnd(label);
resolve();
}, Math.floor(9 * Math.random() + 1) * 1000);
});
}
[1, 2, 3].reduce(async (promise, item) => {
return promise.then(() => call(item));
}, Promise.resolve());
// Output:
// Promise 1: 7.009s
// Promise 2: 9.002s
// Promise 3: 2.013s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment