Skip to content

Instantly share code, notes, and snippets.

@machsix
Last active September 15, 2019 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save machsix/fac4b206418571d6b73760835e261075 to your computer and use it in GitHub Desktop.
Save machsix/fac4b206418571d6b73760835e261075 to your computer and use it in GitHub Desktop.
// https://stackoverflow.com/questions/48014050/wait-promise-inside-for-loop
// let each promise in for to finish
function test(n) {
let promiseChain = Promise.resolve();
for (let i = 0; i < n; i++) {
const makePromise = (j) => () => new Promise((resolve,reject)=> {
setTimeout(resolve, j*1000);
}).then(()=>{
console.log(j);
if (j < 5 ) {
return Promise.resolve(j);
} else {
return Promise.reject(j);
}
});
try {
promiseChain = promiseChain.then(makePromise(i));
} catch (err) {
return Promise.reject(err);
}
}
return promiseChain;
}
test(8).then((x)=>{console.log(x+'x')}).catch((x)=>{console.log(x+' y')})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment