Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 804
ACarter Avatar asked Nov 16 '25 09:11

ACarter


2 Answers

Use destructuring assignment:

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

const obj = { name, location, details };
like image 104
hjrshng Avatar answered Nov 18 '25 04:11

hjrshng


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)
})()
like image 21
Đinh Carabus Avatar answered Nov 18 '25 05:11

Đinh Carabus