I have some code that loops through an array of promises, and outputs the value.
function wait(seconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(seconds);
}, seconds * 1000);
});
}
const promises = [
wait(1),
wait(3),
wait(2),
wait(4),
wait(5),
];
for (var promise of promises) {
promise.then(seconds => console.log(`waited ${seconds} seconds`));
}
The issue with this is that the promise results don't get logged in the order of the array. My expected result is this:
Waited 1 seconds
Waited 3 seconds
Waited 2 seconds
Waited 4 seconds
Waited 5 seconds
And the result was this:
Waited 1 seconds
Waited 2 seconds
Waited 3 seconds
Waited 4 seconds
Waited 5 seconds
So I would like to have something like this
function wait(seconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(seconds);
}, seconds * 1000);
});
}
const promises = [
wait(1),
wait(3),
wait(2),
wait(4),
wait(5),
];
for (var promise of promises) {
// When the promise is resolved, log `Waited ${seconds} seconds`
}
How would I do this?