What’s an async function? A function declared with an async keyword.
async and await keywords goes along together. Basically, you can avoid using promise chains by using these two keywords.
async makes the function behaviour is asynchronous and makes the function return a promise. await, as per the name suggests, make it wait for the promise.
The return value is similar as promise, either resolved with a value or rejected with an error/exception or uncaught within the function.
This is how we write a promise function without async keyword
let promiseEx = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Promise request resolved!");
}, 1000);
});
promiseEx.then(function(value) {
console.log(value);
});
//"Promise request resolved!"
This is how we can convert it to an async promise
async function asyncPromise() {
let promiseEx = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("Promise request resolved!");
}, 1000);
});
console.log(await promiseEx);
}
asyncPromise();
//"Promise request resolved!"
Do you have to have an await expression?
Not really.
You can have none or more than one await expressions.
return value of the await expression = resolved value of the promise
await suspends the function execution till it gets the returned value from promise, either fulfilled value or rejected. That behaviour makes the overall behavior more like synchronous — step by step in a smooth flow. You can also use try / catch blocks with async and await.
await keyword outside of the async function will give you a SyntaxError, it only works inside async function.
Although, you can also use await with JavaScript modules.
async await examples functions promise