Promise.all
在等待同源项目数组(相同数据)的解析时效果很好。使用Promise.all
,以下内容非常方便:
const items = await Promise.all(listOfPromises)
但假设我有以下情况:
const cars = await getListOfCars()
const trucks = await getListOfTrucks()
const airplanes = await getListOfAirplanes()
上面的承诺列表并不相互依赖,可以并行运行。 如何在维护变量名称的同时等待所有承诺完成?
理想情况下,我应该能够做到以下几点:
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
我可以构建我的代码,以便仍然可以参考解析值的变量名称吗?