Async/Await in JavaScript

The async/await is a new syntax for handling asynchronous operations in JavaScript, introduced in ECMAScript 2017. The async keyword is used to indicate that a function is asynchronous and will return a Promise, and the await keyword is used to wait for the resolution of a Promise within an async function.

async keyword in JavaScript

The async keyword in JavaScript is used to declare an asynchronous function, which is a function that returns a promise and can be await-ed. An asynchronous function is useful when you have a function that performs a long-running operation, such as making an API request, and you don't want to block the execution of the rest of the code while waiting for that operation to complete.
async function myAsyncFunction() { return 'Hello, world!'; }
myAsyncFunction().then(result => console.log(result)); // Output: "Hello, world!"
In the above example, myAsyncFunction is an asynchronous function that returns a Promise with the resolved value of "Hello, world!". When the function is called, it immediately returns a Promise that can be accessed using the .then() method to retrieve its resolved value. Note that the async keyword must be used in conjunction with the await keyword. An asynchronous function that doesn't use await will run immediately and return a promise that resolves immediately, which is not very useful.

await keyword in JavaScript

The await keyword is utilized to pause execution until a Promise has been resolved, before proceeding to the next line of code. It must be used within an async function as it cannot be utilized elsewhere. Following example shows how you can use the await keyword to wait for a Promise to resolve:
async function fetchData() { const response = await fetch(''); const data = await response.json(); return data; }
In the above example, the fetchData function uses the fetch API to make a request to an API endpoint and retrieve data. The await keyword is used to wait for the Promise returned by fetch to resolve before moving on to the next line of code. The await keyword is also used to wait for the Promise returned by response.json() to resolve before returning the parsed JSON data. By using the await keyword, you can ensure that each asynchronous operation is completed before moving on to the next line of code. This makes your code easier to read and understand, as it appears to run synchronously, even though it is executing asynchronously.

SyntaxError: await is only valid in async function

The await keyword can only be used inside an async function. If you try to use the await keyword outside an async function, you will get a syntax error. Here's an example of what would happen if you tried to use the await keyword outside an async function:
const response = await fetch(''); // SyntaxError: await is only valid in async function

JavaScript async await | simple example

How to Implement JavaScript Async/Await?
Consider the following asynchronous function which returns a Promise that resolves after a given number of milliseconds:
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
You can use async/await to wait for the completion of this function as follows:
async function delayedLog() { console.log('Before delay'); await delay(1000); console.log('After delay'); }
The function delayedLog is asynchronous and returns a Promise, and the call to await delay(1000) waits for the Promise returned by delay to resolve before continuing to the next line of code. Using async/await can make asynchronous code look and behave more like synchronous code, making it easier to write, understand, and debug.

JavaScript async await | complex example

Following is a complex example that demonstrates the use of the async and await keywords in JavaScript:
async function getUserData(userId) { const userResponse = await fetch(`${userId}`); const user = await userResponse.json(); const postsResponse = await fetch(`${userId}/posts`); const posts = await postsResponse.json(); return { user, posts, }; }
getUserData(123) .then(result => { console.log(result.user); console.log(result.posts); }) .catch(error => console.error(error));
In the above example, the getUserData function makes two API requests to retrieve user data and post data for a given user. The await keyword is used to wait for each fetch Promise to resolve before moving on to the next line of code. The resolved data is then combined into an object and returned from the function. Finally, the getUserData function is invoked with a user ID of 123, and the resolved data is logged to the console. If an error occurs, the catch block will be executed to log the error. This example demonstrates how you can use the async and await keywords to write complex asynchronous code in a way that is easy to read and understand. The use of the await keyword allows you to write asynchronous code that appears to run synchronously, making it easier to debug and maintain.