tc39 / proposal-await-dictionary

A proposal to add Promise.ownProperties(), Promise.fromEntries() to ECMAScript
MIT License
86 stars 4 forks source link

Why not just let the interpreter parallelize awaits in object literals ? #9

Closed fuunnx closed 1 year ago

fuunnx commented 2 years ago

Naively I think this example could be optimized away by the compiler with an internal await Promise.ownProperties() because there would be no semantic change between chaining or parallelizing them :

const x = {
  foo: await foo()
  bar: await bar() 
}

// would be interpreted like this (and be close to what's assumed by most beginners) :
const x = await Promise.ownProperties({
  foo: foo()
  bar: bar() 
}) 

No need for new constructs and it would be a performance win for old usages

ljharb commented 2 years ago

I mean sure, that particular example wouldn't be helped, because you made the mistake of awaiting them first - iow, it's not actually a promise-valued object, so Promise.ownProperties of it is useless.

There's no possible way to make those be equivalent. If your code asks to await something, it must be so.

ajvincent commented 1 year ago

I agree with @ljharb here. Adding this as an under-the-hood optimization would actually backfire, because

  1. during the transition period while engines are implementing it, you'd have inconsistent behavior which would end up as bug reports
  2. foo() could depend on bar(), which wouldn't work in existing code
  3. a senior engineer reading this would question immediately "wait, why didn't we wait for foo() to resolve before going on to bar()?`

Let me give another example which recently bit me about the await keyword:

await foo ? bar() : baz()

Naively, I thought the await would apply to bar or baz, but it applied to foo. In hindsight, I can see why. In practice, this bug led NodeJS to exit out from under me with no obvious reason. NodeJS's behavior was correct, if you think about "what is the await keyword closest to?".