0

This code works as expected:

services.map(async svc => {
  promises.push(new Promise(async (resolve) => {
    html += `<h2>${svc}</h2>`;

    let journeyDetails = await admin.database().ref(`data`).once('value');

    resolve();
  }));
});

await Promise.all(promises).then(() => {
  return res.send(html);
})

Why does the code below not work? In my eyes it's the same, but the execution order is now incorrect.

Promise.all([
  services.map(async svc => {
    new Promise(async (resolve) => {
      html += `<h2>${svc}</h2>`;

      let journeyDetails = await admin.database().ref(`data`).once('value');

      resolve();
    })
  })
]).then(() => {
  // done - called before finished in this version
}).catch(() => {
  // err
});
jskidd3
  • 4,609
  • 15
  • 63
  • 127
  • You're not returning the promise in the second version. – Phix Feb 11 '19 at 18:14
  • @Phix Just added return and it's still not waiting – jskidd3 Feb 11 '19 at 18:16
  • This looks like a new twist on the [explicit promise antipattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it). – Mark Feb 11 '19 at 18:16

1 Answers1

2

I believe the primary reason that your code doesn't work is that you are passing an array of arrays ([services.map(...)]) to Promise.all, not an array of promises.

However, the code is unnecessarily complex. There is no need to create a promise inside an async function, async functions always return a promise. It should just be:

Promise.all( // <- note the removed [...]
  services.map(async svc => {
    html += `<h2>${svc}</h2>`;
    let journeyDetails = await admin.database().ref(`data`).once('value');
    // more code here
  })
)
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thanks Felix. For the question I removed a bit of non-asynchronous code after the async database function which was important. How would I handle that now in your example as wouldn't this stop that from executing? – jskidd3 Feb 11 '19 at 18:25
  • You can put whatever you want after the `await`. – Felix Kling Feb 11 '19 at 18:26