← Go Back

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() {
}

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)

}

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