async and await in Node.js
In JavaScript, async and await make asynchronous code easier to read and understand. They allow us to write Promise-based code in a style that looks similar to normal sequential code.
1. What are async and await?
The async and await keywords are used to work
with Promises in JavaScript.
asyncis used to declare an asynchronous function.awaitpauses that async function until a Promise settles.- After the Promise fulfills,
awaitgives us its result. - If the Promise rejects, the error can be handled using
try...catch.
async means the function works with asynchronous results.
await means wait for the Promise's result inside that
async function.
Example: At CIIT Training Institute, Samadhan requests course details from Pradnya. Instead of processing the result immediately, the program can await the Promise and then display the details.
2. Understanding async
The async keyword declares an asynchronous function.
An async function always returns a Promise.
async function greet() {
return "Welcome to CIIT Training Institute!";
}
greet().then((message) => {
console.log(message);
});
Output
Welcome to CIIT Training Institute!
Explanation
async function greet()declares an async function.- The function returns a string.
- JavaScript makes that returned value the fulfillment value of a Promise.
.then()receives the fulfilled value and displays it.
3. Understanding await
The await keyword waits for a Promise to settle before
continuing the async function. When the Promise fulfills, await
produces its result.
function getCourse() {
return Promise.resolve("Node.js");
}
async function displayCourse() {
let course = await getCourse();
console.log("Course Name: " + course);
}
displayCourse();
Output
Course Name: Node.js
Explanation
getCourse()returns a fulfilled Promise.await getCourse()obtains the Promise's result.- The result is stored in the
coursevariable. - The course name is displayed using
console.log().
4. Flow of async and await
5. Practical Example
Samadhan wants to know whether Pradnya has completed a course report at CIIT Training Institute. The function returns a Promise, and Samadhan waits for the result before displaying the message.
function getReport() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Pradnya completed the course report.");
}, 2000);
});
}
async function showReport() {
console.log("Samadhan is waiting for the report...");
let report = await getReport();
console.log(report);
console.log("Samadhan received the report.");
}
showReport();
Output
Samadhan is waiting for the report... Pradnya completed the course report. Samadhan received the report.The report message appears after approximately 2 seconds.
Step-by-step explanation
getReport()creates and returns a Promise.setTimeout()schedules the report result after about two seconds.showReport()displays the waiting message.await getReport()waits for the report Promise within the async function.- When the Promise fulfills, the report is displayed.
- The final message confirms that Samadhan received the report.
6. Error Handling using try...catch
Sometimes an asynchronous operation fails. We can use
try...catch with await to handle a rejected
Promise and prevent the error from going unhandled.
function getCourseResult() {
return Promise.reject("Course result is not available.");
}
async function displayResult() {
try {
let result = await getCourseResult();
console.log(result);
} catch (error) {
console.log("Error: " + error);
}
}
displayResult();
Output
Error: Course result is not available.
Explanation
getCourseResult()returns a rejected Promise.- The rejection is thrown at the
awaitexpression. - The
catchblock receives the error. - The error message is displayed instead of leaving the rejection unhandled.
7. Using finally with async and await
The finally block executes after the try/catch flow,
whether the operation succeeds or fails. It is useful for cleanup
tasks such as hiding a loading indicator.
async function processAdmission() {
try {
let message = await Promise.resolve(
"Samadhan's admission is confirmed."
);
console.log(message);
} catch (error) {
console.log("Error: " + error);
} finally {
console.log("Admission process completed.");
}
}
processAdmission();
Output
Samadhan's admission is confirmed. Admission process completed.
8. Sequential Execution with await
When multiple operations depend on one another, we can await each operation in sequence.
function getStudent() {
return Promise.resolve("Pradnya");
}
function getStudentCourse(student) {
return Promise.resolve(student + " is learning Node.js.");
}
async function displayStudentDetails() {
let student = await getStudent();
console.log("Student: " + student);
let course = await getStudentCourse(student);
console.log(course);
}
displayStudentDetails();
Output
Student: Pradnya Pradnya is learning Node.js.
Here, the program waits for the student name first. It then passes that name to the second function and waits for the course information.
9. Difference between Promises and async/await
| Promises | async/await |
|---|---|
Often uses .then() and .catch(). |
Uses await and commonly try...catch. |
| Can use method chaining to process results. | Can make sequential asynchronous logic easier to read. |
| Promise-based asynchronous approach. | Syntax built on top of Promises. |
Error handling can be done with .catch(). |
Error handling can be done with try...catch. |
10. Common Mistakes
| Mistake | Correct Approach |
|---|---|
Using await in an ordinary function. |
Use it inside an async function, or at supported top-level module scope. |
| Assuming an async function returns a plain value. | An async function always returns a Promise. |
| Ignoring a possible rejection. | Handle errors using try...catch or a Promise rejection handler. |
| Awaiting independent operations one after another unnecessarily. | Consider Promise.all() when the operations can safely run concurrently. |
11. Important Points to Remember
asyncdeclares an asynchronous function.- An async function always returns a Promise.
awaitobtains a fulfilled Promise's result.- A rejected Promise can be handled using
try...catch. finallyis useful for cleanup after success or failure.- Await pauses the current async function, not the entire program.
- async/await makes many asynchronous workflows easier to read.
Summary
In this lesson, we learned how to declare async functions, use await with Promises, handle errors using try...catch, execute cleanup code using finally, and process dependent asynchronous operations in sequence. Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate practical uses of async and await in JavaScript.