从 Promise.all 解构为对象

ACa*_*ter 3 javascript destructuring node.js promise

我发现自己现在写了很多代码,比如

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

这是相当难看的。我希望有类似的东西

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

但这失败了。有没有一种优雅的方法来进行这样的解构?

Ha *_* Ja 11

使用解构赋值

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

const obj = { name, location, details };
Run Code Online (Sandbox Code Playgroud)


sub*_*nid 6

确实有效。您只需在此处添加分号即可。

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