Skip to content

Instantly share code, notes, and snippets.

@ahallora
Last active February 15, 2020 20:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahallora/d52f9abd2c55ed368d411e6017062896 to your computer and use it in GitHub Desktop.
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)
/*
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