(English is not my native so please pardon my English in advance if you find any)
At this point I'm pretty comfortable with Promises and Async await function, I also know how to use Promise.all (which just waits for all the promises inside to resolve first and then extract the value from all the promises and then return an array using the .then's function with those values.)
Now I'm wondering how does for await of work under the hood.
I've just written this code:
async function f() {
let p1 = new Promise(function (r) {
setTimeout(r, 3000, 1)
})
let p2 = new Promise(function (r) {
setTimeout(r, 2000, 2)
})
let p3 = new Promise(function (r) {
setTimeout(r, 1000, 3)
})
let arrayOfPromises = [p1, p2, p3];
for await (let p of arrayOfPromises) {
let data = await p;
console.log(data)
}
}
f();
Now my question is what happens when it hits the first iteration, it will hit an await keyword, and await immediately returns a pending promise, so is the code below technically evaluated to a pending promise in each iteration?
{
let data = await p;
console.log(data)
}
So i'm confused whats going on really, for the first iteration, a setTimeout will be registered for 3 seconds, 2 for the second and 1 for the one. Since we have no sync code, all the callbacks will be run one by one, p3 will be resolved first, then p2 and then finally p1!
Now intuitively I would think this code "console.log(data)" will be put into the micro task queue once p1, p2, p3 are resolved and since our p3 was resolved first, we should get 3, 2, 1 but we're getting 1, 2, 3, so whats lacking in my understanding?
(Obviously code is not put into the microtask queue, its the functions that do so maybe its doing something like .next() like a generator function does but I think that doesnt matter here)
It seems like with for await of, the first promise will be logged first no matter what how quickly or lately its resolved compared to other promises in the iteration, so whats really going on?