Why can't we use await outside async functions? Why do we need callbacks, promises and await? What are the potential problems with a wrongly coded await? What do we mean when we define a function 'async'?
To prevent from being blocked by long running tasks, JavaScript has callback functions. Callback functions allow us to execute things after a certain time consuming code finishes without stopping for that time consuming code to finish.
A callback function is something we pass to another function expecting it to be executed later by this other function.
Promises are a more elegant way to write callbacks.
Await is a more elegant way to get Promise results than promise.then().
Since await blocks executing the following lines till the promise resolution, its wrong use may block things that shouldn't be blocked.
Async enables us to tell the JavaScript engine what to block until the awaited promise resolves.
If an await at the top level were allowed, it could block the JS engine from doing anything else.
Restricting await to be used inside async functions (a) Mandates us to specify what part of our code should be blocked until the awaited task finishes and (b) Ensures that we do not inadvertently write code that causes the JavaScript engine to be unresponsive.
Want to be notified via email when a new explainer is added?
Submit
< of >
Want to be notified when I add a new explainer?
Submit
I create about one or two of these every month (whenever I find time between my webdev work) & you can unsubscribe at any time. 💨
Copyright (c) 2017-2024 Tezify All Rights Reserved. Created in India. GSTIN : 24BBQPS3732P1ZW.