I'm trying to build an array of objects where some of the fields need remote data. It all works with awaits inside the loop but I'm interested in optimising this. I wrote the following proof-of-concept:
async function p1(x) { // the first remote data
return new Promise((resolve) => {
setTimeout(() => {
resolve(`p1-${x}`);
}, 250);
});
}
async function p2(x) { // the second remote data
return new Promise((resolve) => {
setTimeout( () => {
resolve(`p2-${x}`);
}, 250);
});
}
async function t(n) {
return { a: await p1(n), b: await p2(n), c: n };
}
async function r() {
const results = new Map();
for (let n = 0; n < 2; n++) {
results.set(n, t(n));
}
await Promise.all(results.values());
console.log('in function', results);
return results;
}
(async () => {
const answers = await r();
console.log('answers', JSON.stringify(answers));
})().catch((e) => {
console.log(e);
});
This is the output from running node (13.x):
in function Map(2) {
0 => Promise { { a: 'p1-0', b: 'p2-0', c: 0 } },
1 => Promise { { a: 'p1-1', b: 'p2-1', c: 1 } }
}
answers {}
So my function r() seems to be doing the right thing but the value returned is empty. What am I not understanding?