How can I rearrange the code below to output 0011223344
instead of 01234<random values>
? I'm relatively new to promises and don't know how to batch the promises in a way that the second one only executes when the first one is resolved.
function getPromise(value) {
return new Promise(function(resolve, reject) {
console.log(value);
setTimeout(function () {
resolve(value);
}, Math.random() * 1000);
});
}
for (var i = 0; i < 5; i++) {
getPromise(i).then(console.log);
}
EDIT
In the real scenario the number of promises is random and unpredictable. Since promises inner code start to being executed immediately after creation, I can't have something like a promises array to iterate over, for example.
I guess that's the reason because I couldn't make it work with Promise.all
.