JS Async/Await

HTML
CSS
C#
SQL

Async Function and await Keyword

In JavaScript, the async keyword is used to define an asynchronous function. An async function always returns a Promise, and the value to which the Promise is resolved is the value that the async function returns.

Syntax of Async Function:

Here, functionName is the name of the function, and parameters are the parameters passed to the function.

Example: Async Function

// Async function example
async function f() {
    console.log(‘Async function.’);
    return Promise.resolve(1);
}
f();
// Output: Async function.

The async function returns a Promise, and in this example, it resolves to the value 1.

await Keyword:

The await keyword is used inside an async function to wait for the completion of an asynchronous operation. It can only be used within an async function, and it pauses the execution of the function until the Promise is resolved or rejected.

Syntax of await:

let result = await promise;

Example:

// a promise
let promise = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve(‘Promise resolved’);
    }, 4000);
});

// async function
async function asyncFunc() {
    // wait until the promise resolves
    let result = await promise;
    console.log(result);
    console.log(‘hello’);
}

// calling the async function
asyncFunc();

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:

Promise resolved
hello

Key Points:

– async/await is a powerful feature in JavaScript for handling asynchronous code in a more synchronous-like manner.
– It improves code readability and makes asynchronous code look more like traditional synchronous code.
– await can only be used inside an async function.

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

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

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