0

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?

6
  • If this isn't the best way to do what I'm trying to do, then I'm open to suggestions!
    – Julian
    Commented Feb 26, 2020 at 8:56
  • Only problem is that you can't meaningfully stringify a Map like that Commented Feb 26, 2020 at 8:56
  • You're returning the Map instead of the result of await Promise.all Commented Feb 26, 2020 at 8:56
  • Because your attempt to stringify the Map is the only problem with the code Commented Feb 26, 2020 at 9:03
  • @CertainPerformance ah, yes. The problem was just that!
    – Julian
    Commented Feb 26, 2020 at 9:03

0

Browse other questions tagged or ask your own question.