Writing a demo script to understand promises I have enclosed several promises (using promises.all () to continue after all promises are resolved) inside a then (). Then () s nested promises are not allowed:
var Promise = require("bluebird");
var array = [];
new Promise(function(resolve, reject) {
setTimeout(function() {
for (var i = 5 - 1; i >= 0; i--) {
array.push(returnapromise());
console.log("pushed promise number", i, "onto array");
}
resolve();
}, 300);
})
.then(function() {
new Promise.all(array).then(function() {
console.log("\nall done\n");
});
});
var returnapromise = function() {
return new Promise(function(yolo) {
new Promise(function() {
setTimeout(function() {
console.log("async function within nested promise");
}, 200);
})
.then(function() {
setTimeout(function() {
console.log("async function within then one")
}, 100);
})
.then(function() {
setTimeout(function() {
console.log("async function within then two")
yolo();
}, 50);
});
})
};
However, the desired goal can be achieved using callbacks inside a nested promise, for example:
var Promise = require("bluebird");
var array = [];
new Promise(function(resolve, reject) {
setTimeout(function() {
for (var i = 5 - 1; i >= 0; i--) {
array.push(returnapromise());
console.log("pushed promise number", i, "onto array");
}
resolve();
}, 300);
})
.then(function() {
new Promise.all(array).then(function() {
console.log("\nall done\n");
});
});
var returnapromise = function() {
return new Promise(function(yolo) {
new Promise(function() {
setTimeout(function() {
console.log("async function within nested promise");
one()
}, 200);
var one = function() {
setTimeout(function() {
console.log("cb one")
two();
}, 100);
};
var two = function() {
setTimeout(function() {
console.log("cb two")
yolo();
}, 50);
};
})
})
};
How can I write nested promises that then () s will really be resolved?
source
share