Last active
February 15, 2020 20:27
-
-
Save ahallora/d52f9abd2c55ed368d411e6017062896 to your computer and use it in GitHub Desktop.
How to properly nest functions returning Promises (ECMA6) in node.js (Nested Promises example)
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
/* | |
How to properly nest functions returning Promises (ECMA6) in node.js (Nested Promises example) | |
generated output (with 1 second ticks) => | |
p1 function | |
p2 function | |
p3 function | |
p3 done | |
p2 done | |
p1 done | |
*/ | |
function first() { | |
return new Promise(function(resolve, reject) { | |
setTimeout(function() { | |
console.log('p1 function'); | |
var p2 = second().then(function(){ | |
console.log('p2 done'); | |
resolve(); | |
}); | |
}, 1000); | |
}); | |
} | |
function second() { | |
return new Promise(function(resolve2, reject2) { | |
setTimeout(function() { | |
console.log('p2 function'); | |
var p3 = third().then(function(){ | |
console.log('p3 done'); | |
resolve2(); | |
}); | |
},1000); | |
}); | |
} | |
function third() { | |
return new Promise(function(resolve3, reject3) { | |
setTimeout(function() { | |
console.log('p3 function'); | |
resolve3(); | |
},1000); | |
}); | |
} | |
first().then(function() { | |
console.log('p1 done'); | |
}) | |
.catch(function(e) { | |
console.log('error', e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment