javascriptnode.jspromisedestructuring

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?


Solution

  • 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)
    })()