My code
const promises = [];
for (let i = 1; i < 4; i ) {
promises.push(
new Promise((res, _) => {
setTimeout(async () => {
res(i);
}, 2000);
})
);
}
(async () => {
for (let promise of promises) {
const r = await promise;
console.log(r);
}
})();
CodePudding user response:
When you create a new Promise, the internal function of that promise runs as soon as it gets the opportunity to.
Instead, you could do something like this to make the internal function wait until it's called from your second loop:
const promiseFuncs = [];
for (let i = 1; i < 4; i ) {
promiseFuncs.push(
() => new Promise((res, _) => {
setTimeout(async () => {
res(i);
}, 2000);
})
);
}
(async () => {
for (let promiseF of promiseFuncs) {
const r = await promiseF();
console.log(r);
}
})();