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)
})()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With