Async await in JavaScript
The function that is declared with the async keyword is known as the async function in JavaScript. The await keyword is used inside the async function to make the asynchronous code to be written simple way.
Following are some facts about Async await in JavaScript:
async function always returns promise
async function getUsername() { return "Joe Smith" }; console.log(getUsername()); // Ouput : Promise {: "Joe Smith"}
We can use then chain with async function
async function getUsername() { return "Joe Smith" }; getUsername().then((name) => console.log(name)); // Ouput : Joe Smith
Explicitly return promise from async
async function getUsername() { return Promise.resolve('Joe Smith'); }; getUsername().then((name) => console.log(name)); // Ouput : Joe Smith
Await operator
The await operator works inside an async function and is used to wait for a Promise or an expression until that promise settles and returns the result.
Example of async/await systax
async function getUser() { const result = {}; const promise = new Promise((resolve, reject) => { setTimeout(() => resolve('Joe Smith'), 1000) }); result['name'] = await promise; result['email'] = 'joe@example.com'; return result; } getUser().then((obj) => console.log(obj)); // Output: {name: "Joe Smith", email: "joe@example.com"}
In the above getUser function, we are expecting a user object but the user name is a promise that needs to be resolved to get the full user object. In this case, we can easily use an await operator to resolved the promise first and then return the user object.
Without await keyword
async function getUser() { const result = {}; const promise = new Promise((resolve, reject) => { setTimeout(() => resolve('Joe Smith'), 1000) }); result['name'] = promise; result['email'] = 'joe@example.com'; return result; } getUser().then((obj) => console.log(obj)); // Output: {name: Promise, email: "joe@example.com"}
Without await keyword the user name returns with a promise that resolves later.
await can not be used with regular functions
function getUser() { await new Promise((resolve, reject) => { setTimeout(() => resolve('Joe Smith'), 1000) }); } getUser().then((name) => console.log(name)); // Error: Uncaught SyntaxError: await is only valid in async functions and the top-level bodies of modules
If we try to use await keyword with a regular function then it throws a syntax error.