I'm trying to build an array of objects where some of the fields need remote data. I wrote the following proof-of-concept and it works but the parallel arrays feel messy. Suggestions for something that keeps the keys and promises together would be appreciated:
async function p1(x) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`p1-${x}`);
}, 250);
});
}
async function p2(x) {
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 keys = [];
const values = [];
for (let i = 0; i < 2; i++) {
const key = `k${i}`
keys.push(key);
values.push(t(key));
}
const x = await Promise.all(values);
const results = {};
for (let i = 0; i < keys.length; i++) {
results[keys[i]] = x[i];
}
return results;
}
(async () => {
const answers = await r();
console.log('answers', answers);
})().catch((e) => {
console.log(e);
});