1

Promise.all works great when waiting for a resolution for an array of homogenous items (same data). With Promise.all the following is very convenient:

const items = await Promise.all(listOfPromises)

But suppose I have the following scenario:

const cars = await getListOfCars()
const trucks = await getListOfTrucks()
const airplanes = await getListOfAirplanes()

The above list of promises is not dependent on each other and can run in parallel. How can I await for all the promises to finish while maintaining their variable names?

Ideally, I should be able to do the following:

const cars = await getListOfCars()
const trucks = await getListOfTrucks()
const airplanes = await getListOfAirplanes()

await Promise.all([cars, trucks, airplanes])

// Once this is done, I'd like to be able to refer to the resolved promises by their variable names but that does not work since I suspect placing them into the array above copies them.

console.log(cars); // Still a promise instead of a value. I'd like for it to be the value

Who can I structure my code so that I can still refer to the variable names for the resolved values?

dipole_moment
  • 5,266
  • 4
  • 39
  • 55
  • Use `Promise.all()`, that's what it's for. `async`/`await` semantics serialize your code, that's what they are for. (How can three promises depend on each other when they do not take each other's input? And how can they both run in parallel and depend on each other?) – Tomalak Oct 24 '17 at 16:42
  • Your last example is wrong to me, the first 3 awaits will block your code (truck won't be executed until cars is done). `Promise.all` does it for you already, there is no need to handle more async / awaits in your last example, and cars will be accessible after the await. If you want to wrap each specific callback you should either handle the promise.all callback or make your own wrapper. – briosheje Oct 24 '17 at 16:44
  • 4
    *"`Promise.all` works great when waiting for a resolution for an array of homogenous items (same data)."* The data need not be homogenous at all, there's nothing about `Promise.all` that requires or promotes that. `const [cars, trucks, airplanes] = await Promise.all([getListOfCars(), getListOfTrucks(), getListOfAirplanes()]);` runs the async operations in parallel, waits for them all to finish (or for one of them to fail), and assigns the results to the three constants. See the linked question's answers for more about why multiple individual `await`s aren't likely to be what you want. – T.J. Crowder Oct 24 '17 at 16:44
  • 1
    Ahah! @T.J.Crowder got what I was saying. Yes, that is exactly what I was looking for. Thank you. – dipole_moment Oct 24 '17 at 16:51

0 Answers0