Last active
March 21, 2017 12:24
-
-
Save iamso/0983e547b7b007d821bd95f01fe15890 to your computer and use it in GitHub Desktop.
Nested Promise chain
This file contains 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
// the array to loop through | |
const arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; | |
// start with a resolved promise | |
let p = Promise.resolve(); | |
// loop through the array | |
for (let i of arr) { | |
// create promise chain | |
p = p.then(() => { | |
// return the promise for chaining | |
return functionWithPromise(i); | |
}); | |
} | |
// dummy function with promise | |
function functionWithPromise(text) { | |
// return a promise | |
return new Promise((resolve, reject) => { | |
// start the function | |
console.log(`start promise: ${text}`); | |
// simulate asyncronous activity | |
setTimeout(() => { | |
// end the function | |
console.log(`end promise: ${text}`); | |
// resolve the promise | |
resolve(text); | |
}, 1000); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment