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
Top comments (6)
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 aPromise<number>
in the end. Which can simplify asynchronous function definitions from thisto this
Of course, this will work with anything.
Thank you Amin!
Async is supposed to come before the function keyword
Yes you are right, gonna correct my mistake right away. Thank you.
Really good note didn't know this
Nice summary! :)