2 回答
TA贡献1802条经验 获得超6个赞
如注释中所述,您可以使用数组析构函数而不是使用对象析构函数:
(async () => {
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, "foo");
});
// get all elements as variables
const [p1, p2, p3] = await Promise.all([promise1, promise2, promise3]);
console.log(p1, p2, p3);
})();
TA贡献1777条经验 获得超3个赞
如果不是很明显,如果您可以按串行顺序运行承诺,则可以内联它们 -await
const main = async () =>
{ const a = await mock("one")
const b = await mock("two")
const c = await mock("three")
const d = await mock("four")
console.log(a, b, c, d)
}
// test funcs
const rand = n =>
Math.floor(Math.random() * n)
const mock = (x) =>
new Promise(r => setTimeout(r, rand(1000), x))
// run
console.log("loading...")
main().catch(console.error)
// loading...
// one two three four
如果您想并行运行承诺,但按名称检索赋值,我们可以为我们进行连接 -fromDescriptor
const fromDescriptor = (desc = {}) =>
Promise.all(
Object
.entries(desc)
.map(([ k, px ]) => px.then(x => [ k, x ]))
)
.then(Object.fromEntries)
const main = async () =>
{ const init =
{ a: mock("one")
, b: mock("two")
, c: mock("three")
, d: mock("four")
}
const { a, b, c, d } =
await fromDescriptor(init)
console.log(a, b, c, d)
}
// test funcs
const rand = n =>
Math.floor(Math.random() * n)
const mock = (x) =>
new Promise(r => setTimeout(r, rand(1000), x))
// run
console.log("loading...")
main().catch(console.error)
// loading...
// one two three four
添加回答
举报