DEV Community

Discussion on: A key difference between .then() and async-await in JavaScript

Collapse
sainig profile image
Gaurav Saini

RE: async generators
This is somewhat an advanced topic that I have not used in a lot of projects, but it is very useful when handling multiple data emissions from an asynchronous operation/source (eg: continuous user interaction), kind of like streams. A good syntax to handle this is also the for await, it is better than awaiting inside of a loop, but unfortunately it doesn't fit quite well in every use case, hence the low popularity

for await (let val of myIterator) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

I can't remember some good code example, will have to look for some good examples/use-cases. I did use it in a small game I created using Pixi for the game loop or ticker or whatever you call that thing, but later replaced it with RxJS.

It was my understanding that async ensures that a function returns a promise by creating a new Promise only if a "thing" within the function is not a Promise.

You are correct, I forgot to include that detail.
But, like I said, it must be used with caution and one should not needlessly use it in front of everything.

RE: "recipe for a blackout"
I might have been a bit too dramatic there, but let me explain. See my note above for microtasks. it is difficult, but if someone managed to queue new microtasks (creating new Promises is one way of queuing a microtask) faster than the event loop can process them, then the loop gets stuck at the microtask queue and it will be stuck infinitely processing the microtasks.

Two important points here are:

  • I think it is impossible to completely halt the event loop at the microtask queue step, but the worst case scenario would be to have janky/laggy user experience even for very trivial tasks like reponding to click events, keyboard events, rendering DOM elements, etc.
  • async/await is not at fault here at all, this can be done with Promises and .then too, but it seems like it would go unnoticed easily with async/await as they can be used within loop bodies while .then can't be, atleast not the way you would expect it to behave (another reason I don't use await in loops)

I don't discourage the use of one asynchronous construct over the other, just that we should use things with caution, so that they don't backfire and atleast understand the basic working of anything before we use it