DEV Community

Pachi 🥑
Pachi 🥑

Posted on • Edited on • Originally published at pachicodes.com

Basics of Async and Await

Good day, today I will share my notes about Async/Await.

Async/await functions is new feature that came with ES2017 (ES8), and it allow us to write synchronous-looking code that performs asynchronous tasks.
Using Async/Await can make your code easier to read and understand and allows you to use Promises in a Sync way without blocking the main thread.

A bit of Syntax
Specify the word async before a functions makes this function return a Promise.

async function() {
}
Enter fullscreen mode Exit fullscreen mode

Await works only inside an Async function and it returns the Promise's result after it is solved. As an example, Await tells JS "wait" until the Promise is solved before going on with the rest of the code.

const example = async function() {
const promise = new Promise(function(resolve, reject) {
setTimeout(resolve, 999, 1)
})
const response = await promise
console.log(response)

}
Enter fullscreen mode Exit fullscreen mode

Handling error
There is a little delay between the Promise being reject and the error being fired, so it is a good strategy to use "try/catch" to deal with error, where the catch will, guess what? Yes, it will Catch any error inside the try block.

This is just my short Notes on the topic as usual, so all extra comments are super welcome as always!

Happy Monday and Thanks for reading,
XOXO

Top comments (6)

Collapse
 
aminnairi profile image
Amin • Edited

Hi there, great set of notes on the subject!

I would add to your notes that returning any value from any async function makes it a promise as well. So returning a number will make it a Promise<number> in the end. Which can simplify asynchronous function definitions from this

function promiseNumber() {
    return Promise.resolve(123);
}

to this

async function promiseNumber() {
    return 123;
}

Of course, this will work with anything.

Collapse
 
pachicodes profile image
Pachi 🥑

Thank you Amin!

Collapse
 
mateiadrielrafael profile image
Matei Adriel

Async is supposed to come before the function keyword

Collapse
 
aminnairi profile image
Amin

Yes you are right, gonna correct my mistake right away. Thank you.

Collapse
 
davjvo profile image
Davmi Jose Valdez Ogando

Really good note didn't know this

Collapse
 
webdeasy profile image
webdeasy.de

Nice summary! :)