DEV Community

Discussion on: Why async code is so damn confusing (and a how to make it easy)

Collapse
 
crazy4groovy profile image
crazy4groovy • Edited

There's one thing to recognize about await, is that it doesn't "hurt" anything!

So:

const main = async () => {
  action1()
  await sleep(1000)
  action2()
}

and

const main = async () => {
  await action1()
  await sleep(1000)
  await action2()
}

will always be the same.

In fact, event if action1 and action2 returns a literal value (let's say "hi!"):

const main = async () => {
  const a = action1()
  await sleep(1000)
  const b = action2()
  console.log(a, b)
}

and

const main = async () => {
  const a = await action1()
  await sleep(1000)
  const a = await action2()
  console.log(a, b)
}

will always be the same! (mind. blown.)

I for one think you are onto something, where the lines between async and sync can almost always be blurred away. But I think it would take a new syntax. For example:

const main = () => {
  const a =: action1()
  =: sleep(1000)
  const b = action2()
  console.log(a, b)
}

where =: means "resolve the value", and all arrow function are inherently "async".

(This is kind of like pointer logic, where you either mean "give me the address" or "give me the value at the address"; but here its "give me the promise" or "give me the value of the promise")

Collapse
 
joelnet profile image
JavaScript Joel

That's true, you could just await everything. You can even do this:

const x = await 5

In the case of this problem:

// await `action()`
await thing().action()

// await `thing()`
(await thing()).action()

You could do this and not worry.

// await all the things
await (await thing()).action()

But I would probably go insane.

Collapse
 
vhoyer profile image
Vinícius Hoyer

while it is true you could await every thing, there is a difference. the await operator will always wait till the next tick to start checking for the resolving of a promise, even if your promise is a literal. But thats just what I read somewhere that I don't remember where, sorry for the lack of reference, yet I'm pretty confident in the information.

Thread Thread
 
joelnet profile image
JavaScript Joel

I believe you were correct about this. Adding extraneous awaits could have a performance impace.