Last active
September 15, 2019 07:24
-
-
Save machsix/fac4b206418571d6b73760835e261075 to your computer and use it in GitHub Desktop.
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
// 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