Skip to content

Instantly share code, notes, and snippets.

@samokoder
Created February 10, 2019 13:43
Show Gist options
  • Save samokoder/9808e47a8a61f18a61c5c735607f2e02 to your computer and use it in GitHub Desktop.
Save samokoder/9808e47a8a61f18a61c5c735607f2e02 to your computer and use it in GitHub Desktop.
Execute multiple promises one after another (not in parallel)
// see https://stackoverflow.com/a/24985483
const fetchList = list => {
return list.reduce((promise, item) => {
return promise.then(() => {
// or any other promise
return new Promise((resolve) => {
console.log(`delay for ${item} secs`);
setTimeout(() => {
resolve();
}, item * 1000);
});
});
}, Promise.resolve());
};
const listDelays = '123456'.split('').map(() => Math.round( Math.random() * 10 ) + 1);
fetchList(listDelays).then(() => console.log('job 1 finished'));
// 2nd method
function asyncMethod() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('item done');
resolve();
}, 3000);
});
}
let chain = Promise.resolve();
const asyncArray = '123'.split('').map(() => asyncMethod);
for(const func of asyncArray) {
chain = chain.then(func);
}
chain.then(() => console.log('job 2 finished'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment