Async/Await
For management of asynchronous operations, we have Promise
s-- so everything should be good, right?
There must be a better way to write Promises from what we saw above. The syntax still requires reasoning about multiple states of resolution, and requires effort to understand if there are many Promises being generated. Is there something better?
That is where async
/await
comes in. This is a special syntax (really just a nicer interface to Promise
s) that allows us to handle them in a much easier manner. To use async, you simply need to prefix the keyword before any function and it will return a promise. Even the other values within that function will be wrapped inside the promise. This allows us to refrain from using the Promise
keyword by ourselves, since it's done automatically behind the scenes.
1async function hello(){
2 try{
3 return("Hello")
4 }
5 catch(error){
6 return("Boo! You have a " + error)
7 }
8}
9hello().then(value => console.log(value));
Remember the hello()
method we wrote earlier? Look how easy to read it has become just by using the async
keyword.
Await
is another keyword that is used in conjunction with async. Like the literal meaning of await, this keyword allows us to suspend an asynchronous function. It works only inside an async
function because, at the end of the day, it is suspending an async function.
xxxxxxxxxx
async function hello() {
return greeting = await new Promise((resolve, reject) => {
setTimeout(() => resolve("Hello"), 1000)
});
};
console.log("Before execution");
hello().then((value) => console.log(value));
console.log("After execution");