简体   繁体   English

从 Promise.all 解构为对象

[英]Destructuring from Promise.all into object

I find myself at the moment writing a lot of code like我发现自己现在写了很多代码,比如

const arr = await Promise.all([getName(), getLocation(), getDetails()])
const obj = {
    name: arr[0],
    location: arr[1],
    details: arr[2]
}
// send obj to somewhere else

which is quite ugly.这很丑陋。 I was hoping there was something like我希望有类似的东西

const obj = {}
[obj.name, obj.location, obj.details] = await Promise.all([getName(), getLocation(), getDetails()])

but this fails.但这失败了。 Is there an elegent way to do the destructuring like this?有没有一种优雅的方法来进行这样的解构?

Use destructuring assignment :使用解构赋值

const [name, location, details] = await Promise.all([getName(), getLocation(), getDetails()]);

const obj = { name, location, details };

It does work.确实有效。 You just have to add a semicolon here.你只需要在这里添加一个分号。

 (async () => { const obj = {}; // <------------------------------ [obj.first, obj.second, obj.third] = await Promise.all([1,2,3]) console.log(obj) })()

await Promise.all([getName(), getLocation(), getDetails()])
    .then(([name, location, details]) => ({ name, location, details }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM