JS Async/Await

Async Function and await Keyword

What Does Async Mean?

The async keyword is used to tell JavaScript that a function will do something that takes time — like waiting for an answer from a server, fetching data, or even waiting for a timer to finish. These operations don’t happen instantly, and async tells JavaScript to wait for these operations without freezing the whole program.

Think of async like saying:

“Hey JavaScript, this function will take a little time to finish, so please don’t stop everything else while it’s running!”

Here’s an example of how to use async:

async function bakeCake() {
console.log(“Starting to bake a cake…”);
// Simulating a task that takes time, like baking a cake.
await new Promise(resolve => setTimeout(resolve, 3000)); // 3 seconds to bake
console.log(“Cake is ready!”);
}

bakeCake();

Code explanation

async function bakeCake()

The async keyword makes bakeCake an asynchronous function. This means it can perform tasks that take time (like waiting) without freezing the entire program.

console.log(“Starting to bake a cake…”);

Prints the message that the cake is starting to bake.

await new Promise(resolve => setTimeout(resolve, 3000));

The await keyword pauses the function until the Promise is resolved. Here, the Promise is resolved after 3 seconds using setTimeout(). This simulates the time taken for the cake to bake.

console.log(“Cake is ready!”);

After the 3 seconds (when the Promise is resolved), this message is printed, indicating the cake is done.

bakeCake();

Calls the bakeCake function to start the process.

Output
JS-Asyn-Men

What Does Await Do?

The await keyword works inside an async function. It tells JavaScript, “Wait for this task to finish before continuing.” It’s like pausing a movie at a specific scene until you’re ready to move to the next one.

Let’s break it down:

        •  The await keyword only works inside async functions.
        •  It makes JavaScript wait for a promise to finish before continuing.

Here’s an example where await is useful:

async function cookDinner() {
console.log(“Cooking dinner…”);
let result = await fetch(“https://fake-api.com/dinner”); // Waiting for the data to come
console.log(“Dinner is ready!”, result);
}

cookDinner();

Code explanation

async function cookDinner()

The async keyword makes cookDinner an asynchronous function. This means the function can handle operations that take time (like waiting for data from a server) without blocking the rest of the program.

console.log(“Cooking dinner…”);

This logs the message “Cooking dinner…” immediately, indicating that the dinner cooking process is starting.

let result = await fetch(“https://fake-api.com/dinner”);

The await keyword pauses the function here until the fetch request completes.

fetch() makes an HTTP request to the given URL (https://fake-api.com/dinner) to retrieve data (in this case, we simulate fetching dinner data from a server).

await ensures that the function waits for the data to come back before moving to the next line.

Once the request completes, the response is stored in the result variable.

console.log(“Dinner is ready!”, result);

After the data is fetched and the promise is resolved, it prints “Dinner is ready!” along with the result (the fetched data).

cookDinner();

This line calls the cookDinner function to start the process.

Example:

// Function that returns a promise
function checkCondition(value) {
// Create a promise
return new Promise((resolve, reject) => {
// Check the condition
if (value > 0) {
// Fulfill the promise if the condition is met
resolve(“Promise is fulfilled!”);
} else {
// Reject the promise if the condition is not met
reject(“Promise is rejected!”);
}
});
}
// Test the promise with different values
checkCondition(5)
.then((result) => {
console.log(result); // Output: Promise is fulfilled!
})
.catch((error) => {
console.error(error); // This won’t be executed for value = 5
});
checkCondition(-2)
.then((result) => {
console.log(result); // This won’t be executed for value = -2
})
.catch((error) => {
console.error(error); // Output: Promise is rejected!
});

In this example, await promise ensures that the asyncFunc function pauses until the promise is resolved, and then it continues with the rest of the code.

Output

Course Video

Practice Scenarios

1. Write a JS Program to check The Condition And Based On the Condition check Whether The Promise is Fulfilled or Not.

The task is to write a JavaScript program that checks a condition and based on that condition, determines whether a promise is fulfilled or not.
1. Create a Promise:
Write a function that returns a promise. Inside this function, check a condition.
2. Fulfill or Reject the Promise:
If the condition is met, fulfill the promise using resolve(). If the condition is not met, reject the promise using reject().

Here's an example program:

// Function that returns a promise
function checkCondition(value) {
// Create a promise
return new Promise((resolve, reject) => {
// Check the condition
if (value > 0) {
// Fulfill the promise if the condition is met
resolve(“Promise is fulfilled!”);
} else {
// Reject the promise if the condition is not met
reject(“Promise is rejected!”);
}
});
}

// Test the promise with different values
checkCondition(5)
.then((result) => {
console.log(result); // Output: Promise is fulfilled!
})
.catch((error) => {
console.error(error); // This won’t be executed for value = 5
});

checkCondition(-2)
.then((result) => {
console.log(result); // This won’t be executed for value = -2
})
.catch((error) => {
console.error(error); // Output: Promise is rejected!
});

Output
JS-Program

2. Write a function delayedResponse that takes a message and a delay time (in milliseconds) as parameters. The function should return a Promise that resolves with the message after the specified delay.

The task is to write a JavaScript function called delayedResponse that takes a message and a delay time as parameters. The function should return a promise that resolves with the message after the specified delay.

1. Write a Function: Define a function called delayedResponse that takes two parameters: message and delayTime.
2. Return a Promise:
– Inside the function, create a promise using the Promise constructor.
– Use setTimeout to delay the resolution of the promise by the specified delayTime.
– Resolve the promise with the provided message after the delay.

Here's an example program:

// Function that returns a delayed promise
function delayedResponse(message, delayTime) {
// Create a promise
return new Promise((resolve) => {
// Use setTimeout to delay the resolution of the promise
setTimeout(() => {
// Resolve the promise with the provided message after the delay
resolve(message);
}, delayTime);
});
}
// Test the delayedResponse function
delayedResponse(“Hello after 2000 milliseconds”, 2000)
.then((result) => {
console.log(result); // Output: Hello after 2000 milliseconds
});

Output

3. Write A JS program To take the Task As Input from the User and Update that Task on the Document and after 5 sec again takes the input from the user to determine if a user has completed its Task or not If the User Enter Yes the print “Promise Fulfilled” in Green color and if no Then Print “Promise Un Fulfilled” in red Color.

The task is to write a JavaScript program that takes a task as input from the user, updates the document with the task, and after 5 seconds, prompts the user to determine if the task is completed. Depending on the user’s input, the program should print “Promise Fulfilled” in green color if the user enters “Yes” and “Promise Unfulfilled” in red color if the user enters “No”.
1. Take Task Input:
– Use prompt to take a task as input from the user.
– Update the document (e.g., a paragraph) with the entered task.
2. Delay and Prompt Again:
– Use setTimeout to delay the next prompt by 5 seconds.
– After the delay, use prompt again to ask the user if the task is completed.
3. Print Results:
– If the user enters “Yes,” print “Promise Fulfilled” in green color on the document.
– If the user enters “No,” print “Promise Unfulfilled” in red color on the document.

Here's an example program:

<!DOCTYPE html>
<html>
<head>
<title>Task Promise</title>
<style>
/* CSS to style the results */
.fulfilled {
color: green;
}
.unfulfilled {
color: red;
}
</style>
</head>
<body>
<p id=”task”></p>
<script>
// Function to take task input and update the document
function takeAndDisplayTask() {
// Take task input from the user
const task = prompt(“Enter your task:”);
// Update the document with the entered task
document.getElementById(‘task’).innerText = `Task: ${task}`;
// After 5 seconds, prompt the user again
setTimeout(() => {
// Prompt to determine if the task is completed
const isTaskCompleted = prompt(“Is the task completed? (Yes/No)”);
// Display results based on user input
if (isTaskCompleted.toLowerCase() === ‘yes’) {
document.getElementById(‘task’).classList.add(‘fulfilled’);
document.getElementById(‘task’).innerText += ‘ – Promise Fulfilled’;
} else {
document.getElementById(‘task’).classList.add(‘unfulfilled’);
document.getElementById(‘task’).innerText += ‘ – Promise Unfulfilled’;
}
}, 5000);
}
// Call the function to start the process
takeAndDisplayTask();
</script>
</body>
</html>

Output

4. Write a function performCalculation that takes two numbers and a math operation (‘add’, ‘subtract’, ‘multiply’, ‘divide’) as parameters. Use async/await to perform the calculation asynchronously and return the result.

The task is to write a JavaScript function called performCalculation that takes two numbers and a math operation as parameters (‘add’, ‘subtract’, ‘multiply’, ‘divide’). The goal is to use async/await to perform the calculation asynchronously and return the result.

1. Write a Function:
Define a function called performCalculation that takes three parameters: num1, num2, and operation.
2. Use Async/Await:
– Inside the function, use async before the function keyword to indicate that this function will contain asynchronous code.
– Use await to pause the execution of the function until the asynchronous calculation is complete.
3. Perform Calculation:
Based on the provided operation, perform the corresponding calculation (addition, subtraction, multiplication, or division) asynchronously.
4. Return Result:
Return the calculated result.

Here's an example program:

// Function to perform calculation asynchronously using async/await
async function performCalculation(num1, num2, operation) {
// Use a switch statement to determine the operation
switch (operation) {
case ‘add’:
// Simulate asynchronous addition
await new Promise(resolve => setTimeout(resolve, 1000));
return num1 + num2;
case ‘subtract’:
// Simulate asynchronous subtraction
await new Promise(resolve => setTimeout(resolve, 1000));
return num1 – num2;
case ‘multiply’:
// Simulate asynchronous multiplication
await new Promise(resolve => setTimeout(resolve, 1000));
return num1 * num2;
case ‘divide’:
// Simulate asynchronous division
await new Promise(resolve => setTimeout(resolve, 1000));
return num1 / num2;
default:
// Return an error for invalid operation
throw new Error(‘Invalid operation’);
}
}
// Example usage
async function calculate() {
try {
const result = await performCalculation(10, 5, ‘add’);
console.log(‘Result:’, result); // Output: Result: 15
} catch (error) {
console.error(‘Error:’, error.message); // This won’t be executed in the example
}
}
// Call the function to start the calculation
calculate();

Output

5. Write a function fetchUserData that simulates fetching user data from an API. Use setTimeout to introduce a delay of 2 seconds before resolving the Promise with mock user data.

The task is to write a JavaScript function called fetchUserData that simulates fetching user data from an API. The goal is to use setTimeout to introduce a delay of 2 seconds before resolving the Promise with mock user data.

1. Write a Function: Define a function called fetchUserData.
2. Use setTimeout:
Inside the function, use setTimeout to introduce a delay of 2 seconds (or 2000 milliseconds).
3. Resolve Promise:
After the delay, resolve the Promise with mock user data.

Here's an example program:

// Function to simulate fetching user data from an API with a delay
function fetchUserData() {
// Return a Promise with setTimeout
return new Promise((resolve) => {
// Introduce a delay of 2 seconds (2000 milliseconds)
setTimeout(() => {
// Resolve the Promise with mock user data
const userData = {
id: 1,
username: ‘john_doe’,
email: ‘john.doe@example.com’,
};
resolve(userData);
}, 2000);
});
}
// Example usage
async function fetchData() {
try {
// Call the function to fetch user data
const user = await fetchUserData();
console.log(‘User Data:’, user);
// Output: User Data: { id: 1, username: ‘john_doe’, email: ‘john.doe@example.com’ }
} catch (error) {
console.error(‘Error:’, error.message);
}
}
// Call the function to start fetching data
fetchData();

Output

6. Async Function Returning a Promise

Objective: Learn how to return a promise from an async function.

       •  Write an async function that returns a promise resolving with a value.
       •  Use await to resolve the promise and get the result.

Here's an example program:

async function getValue() {
return “Promise resolved in async function”;
}

async function fetchData() {
const result = await getValue();
console.log(result); // Output: “Promise resolved in async function”
}
fetchData();

Output

7. Chaining Async Functions

Objective: Chain async functions with await.

       •  Write two async functions, each returning a promise.
       •  Use await to call these functions one after another in a sequential flow.

Here's an example program:

async function taskOne() {
return new Promise((resolve) => setTimeout(() => resolve(“Task 1 completed”), 1000));
}

async function taskTwo() {
return new Promise((resolve) => setTimeout(() => resolve(“Task 2 completed”), 1000));
}

async function performTasks() {
const result1 = await taskOne();
console.log(result1); // Output: “Task 1 completed” after 1 second
const result2 = await taskTwo();
console.log(result2); // Output: “Task 2 completed” after 2 seconds (total)
}
performTasks();

Output

8. Handling Multiple Errors in Async Functions

Objective: Handle multiple errors in async functions using try…catch.

       •  Simulate two async functions that may randomly succeed or fail.
       •  Catch errors from both functions and handle them separately.

Here's an example program:

function fetchData1() {
return new Promise((resolve, reject) => {
const success = Math.random() > 0.5;
setTimeout(() => {
if (success) resolve(“Data 1 fetched”);
else reject(“Error fetching Data 1”);
}, 1000);
});
}

function fetchData2() {
return new Promise((resolve, reject) => {
const success = Math.random() > 0.5;
setTimeout(() => {
if (success) resolve(“Data 2 fetched”);
else reject(“Error fetching Data 2”);
}, 1500);
});
}

async function fetchData() {
try {
const result1 = await fetchData1();
console.log(result1);
} catch (error) {
console.log(error); // Error fetching Data 1
}

try {
const result2 = await fetchData2();
console.log(result2);
} catch (error) {
console.log(error); // Error fetching Data 2
}
}
fetchData();

Output
Frequently Asked Questions

Still have a question?

Let's talk

async/await is a modern syntax for handling asynchronous code in JavaScript, making it easier to read and write compared to Promises or callbacks. Learn more in our JavaScript async await free course video.

Use the async keyword before a function declaration.
Example:

async function fetchData() { 

  let response = await fetch(“https://api.example.com”); 

  return response.json(); 

Explore this in the JS async await with free video tutorial.

The await keyword pauses the execution of an async function until a Promise is resolved or rejected. Discover its usage in the Free JavaScript async await tutorial for beginners.

No, await can only be used inside an async function. However, with top-level await (introduced in ES2022), you can use it in modules. Learn more in the JavaScript async await with free tutorial.

Use a try…catch block to catch errors.
Example:

async function fetchData() { 

  try { 

    let response = await fetch(“https://api.example.com”); 

    return response.json(); 

  } catch (error) { 

    console.error(“Error:”, error); 

  } 

Find detailed examples in the JavaScript async await free course video.

async/await is syntactic sugar for Promises, providing a more synchronous way to write asynchronous code. Discover the differences in the JS async await with free video tutorial.

Yes, you can use Promise.all to execute multiple Promises concurrently and await their results.
Example:

let [data1, data2] = await Promise.all([fetch(url1), fetch(url2)]); 

Explore this technique in the Free JavaScript async await tutorial for beginners.

If an awaited Promise rejects, the function throws an error, which you can catch with try…catch. Learn how to handle this in the JavaScript async await with free tutorial.

Yes, the value returned by an async function is automatically wrapped in a Promise.
Example:

async function getData() { 

  return “Hello”; 

getData().then(console.log); // Output: “Hello” 

Watch practical examples in the JavaScript async await free course video.

While async/await simplifies code, it can sequentially execute operations that could be done concurrently. Use Promise.all for better performance in such cases. Learn performance tips in the JS async await with free video tutorial.