Skip to content

Instantly share code, notes, and snippets.

@iamso
Last active March 21, 2017 12: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 iamso/0983e547b7b007d821bd95f01fe15890 to your computer and use it in GitHub Desktop.
Save iamso/0983e547b7b007d821bd95f01fe15890 to your computer and use it in GitHub Desktop.
Nested Promise chain
// 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