2

If I want to assign two resolved promises to two variables, I can do this:

const [a, b] = await Promise.all([first(), second()])

But assign I have an object with properties, instead of a and b, how can I affect the result to object properties?

This does not works:

const x = {}
const [x.a, x.b] = await Promise.all([first(), second()])

Is there a way to do this?

rap-2-h
  • 30,204
  • 37
  • 167
  • 263
  • 4
    What about just following the `await` with `const x = {a, b};`? Or are you trying to eliminate the `a, b` entirely? – zero298 Sep 11 '18 at 14:24

2 Answers2

3

If you're after a one-liner, I'm sorry to disappoint. Dereferencing assignment is meant for terse object expansion into variables, but not data-mapping between objects.

I would also encourage you to avoid clever code because if it's hard to read it's hard to understand which means it's hard to verify that it's working as expected for all appropriate edge cases.

In this case, adding more lines is trivially easy and clear:

const [a, b] = await Promise.all([first(), second()])

const x = {
  a,
  b
}

as a follow up question, what if you don't want to produce a and b variables within the current scope? For example, what if a and b are already defined and you need to avoid a naming conflict?

In that case, adding a little more code to be explicit is useful:

const [xA, xB] = await Promise.all([first(), second()])

const x = {
  a: xA,
  b: xB
}
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • haha thanks for the detailed answer and the link to "clever" code! My question was motivated by curiosity, not sure I will write this :) (I don't want to bully the reviewers) – rap-2-h Sep 11 '18 at 14:50
2

You can't use const (which declares variables) if you want to assign to properties:

const x = {};
[x.a, x.b] = await Promise.all([first(), second()]);

Notice that the semicolon is necessary here, if you want to omit them and let them be automatically inserted where ever possible needed, you will need to put one at the begin of the line:

const x = {}
;[x.a, x.b] = await Promise.all([first(), second()])
Bergi
  • 630,263
  • 148
  • 957
  • 1,375