DEV Community

Nashmeyah
Nashmeyah

Posted on

Benefits of using async await

Async functions are functions declared with the async keyword, the await is used within the functions scope. Putting the async before the function simply means that it will always return a promise and other values will be wrapped in a resolved promise. Using them allows asynchronous behavior based on promises. This means that what the promise of the function returns will be cleaner and avoiding the need to configure promise chains.

async function foo() {
  return 1
}
Enter fullscreen mode Exit fullscreen mode

is similar to

function foo() {
  return Promise.resolve(1)
}
Enter fullscreen mode Exit fullscreen mode

Await keyword waits until that promise settles and returns a result. If the await is used outside a async functions body, it will throw a SyntaxError. "Code after each await expression can be thought of as existing in a .then callback. In this way a promise chain is progressively constructed with each reentrant step through the function. The return value forms the final link in the chain."(MDN, await 2005-2021, online doc)

In this article, it explains different ways you can use async tasks :https://dmitripavlutin.com/javascript-async-await/

Top comments (0)