How to handle errors when dealing with asynchronous code ?
Last Updated :
04 Nov, 2022
Asynchronous code in Node.js is a code that does not block the execution of code after it. In Synchronous code, the code waits for further code execution until the current operation is not completed and executes from top to down while in asynchronous code, the asynchronous code is executed in a separate thread so that execution of further code is not blocked and thus they are both executed simultaneously. To get a deeper understanding of Asynchronous programming, refer How does asynchronous code work in JavaScript?
Now let us discuss how to handle errors in Asynchronous Code.
Using CallBacks: A Callback Function is a function that is passed as the last parameter in an asynchronous function and a callback is called when the asynchronous function has been executed. The first parameter in any callback function is the error object so they are often referred to as error-first callbacks. If there is no error, the error object is null otherwise it will contain information regarding the error.
Example: In the example below, we use the setTimeout method to make our mod function asynchronous. If b is zero we pass an error saying “Modulo zero is not allowed” otherwise we log the result. This way our callback handles errors every time the mod function is called.
Javascript
<script>
const mod = (a, b, callback) => {
setTimeout(() => {
if (b == 0) {
callback( "Modulo zero is not allowed" );
} else {
callback( null , a % b);
}
}, 0);
};
mod(5, 2, (err, res) => {
if (err) {
console.log(err);
}
else {
console.log( 'The result is ' + res);
}
});
mod(5, 0, (err, res) => {
if (err) {
console.log(err);
}
else {
console.log(`The result is ${res}`);
}
});
</script>
|
Output:
The result is 1
Modulo zero is not allowed
But when we use the callback method we can sometimes get stuck in callback hell. To avoid that we use Promises discussed below.
Using Promises: Promises enable us to handle asynchronous operations in Nodejs without getting stuck in callback hell. A promise is either resolved or rejected. There are two methods then() and catch() after a promise is resolved or rejected. If it is resolved then code in the then() method is executed otherwise we get the error thrown through the catch block.
Example: let us modify the example above and handle errors using promises.
Javascript
<script>
const mod = (a, b) => {
return new Promise((resolve, reject) => {
if (b == 0) {
reject( "Modulo zero is not allowed" );
} else {
resolve(a % b);
}
})
};
mod(5, 2).then((res) => {
console.log(`The result is ${res}`);
}). catch ((err) => {
console.log(err);
});
mod(5, 0).then((res) => {
console.log(`The result is ${res}`);
}). catch ((err) => {
console.log(err);
});
</script>
|
Output:
The result is 1
Modulo zero is not allowed
The code is cleaner now than before when we were using callbacks. Although Promises enabled us to prevent callback hells they have syntax complexity of their own so we got Async functions discussed below.
Using Async/Await: Async/Await makes JavaScript promises easier to work with. It enables us to handle errors using the try-catch block. To use async-await, we just need to create an async function in which we will implement our try-catch block. In the try block, we will await our promise to be completed. If it gets resolved we will get the result otherwise an error will be thrown through the catch block. Await can only be used inside an async function or async callback or async arrow function.
Example:
Javascript
<script>
const mod = (a, b) => {
return new Promise((resolve, reject) => {
if (b == 0) {
reject( "Modulo zero is not allowed" );
} else {
resolve(a % b);
}
});
};
async function _5mod2() {
try {
const res = await mod(5, 2);
console.log(`The result of division is ${res}`);
} catch (err) {
console.log(err);
}
};
_5mod2();
async function _5mod0() {
try {
const res = await mod(5, 0);
console.log(`The result of division is ${res}`);
} catch (err) {
console.log(err);
}
};
_5mod0();
</script>
|
Output:
The result of division is 1
Modulo zero is not allowed
Similar Reads
How to Handle Errors for Async Code in Node.js ?
Handling errors effectively in asynchronous code is crucial for building robust and reliable Node.js applications. As Node.js operates asynchronously by default, understanding how to manage errors in such an environment can save you from unexpected crashes and ensure a smooth user experience. This a
4 min read
How to Write Asynchronous Function for Node.js ?
The asynchronous function can be written in Node.js using 'async' preceding the function name. The asynchronous function returns an implicit Promise as a result. The async function helps to write promise-based code asynchronously via the event loop. Async functions will always return a value. Await
2 min read
How does React Handle Errors in the Component Tree ?
In the older versions of React (before v16), we do not have any feature to handle the React errors which were occurred in the components and these errors are used to corrupt the internal state of the React component. Below are the methods to handle errors in the React component tree: Table of Conten
3 min read
How to handle asynchronous operations in Node ?
NodeJS, renowned for its asynchronous and event-driven architecture, offers powerful mechanisms for handling asynchronous operations efficiently. Understanding how to manage asynchronous operations is crucial for NodeJS developers to build responsive and scalable applications. What are Asynchronous
2 min read
How does asynchronous code work in JavaScript ?
Asynchronous code in JavaScript allows to execute code in the background without blocking the main thread. Asynchronous JavaScript is mainly used for handling tasks like network requests, file operations, and API calls. To understand how asynchronous code works, it's important to first know the conc
4 min read
How to handle asynchronous operations in custom hooks?
Custom Hooks in React are reusable JavaScript functions that enable the encapsulation of stateful logic, promoting cleaner and more modular code in components. When dealing with asynchronous operations in custom hooks, you want to ensure your hook can handle tasks that don't finish immediately, like
3 min read
Asynchronous Patterns in Node.js
Asynchronous programming in NodeJS allows tasks to run in the background without blocking execution, enabling efficient handling of multiple operations. It uses the event loop, callbacks, promises, and async/await to manage non-blocking I/O tasks seamlessly. Understanding Asynchronous ProgrammingAsy
5 min read
How to Handle Errors in React Redux applications?
To handle errors in Redux applications, use try-catch blocks in your asynchronous action creators to catch errors from API calls or other async operations. Dispatch actions to update the Redux state with error information, which can then be displayed to the user in the UI using components like error
4 min read
How to Handle MySQL Connection Errors in NodeJS?
Dealing with MySQL connection errors requires you to look at issues related to establishing, maintaining, and closing connections to the MySQL database. This includes initial connection failure, connection drop detection and recovery, and error handling during query execution. Effective error handli
2 min read
How to handle errors in Promise.all ?
To handle errors in Promise.all(), you need to understand that it fails immediately if any of the promises reject, discarding all resolved values. This behavior can lead to incomplete operations and potential application crashes. The best way to manage errors in Promise.all() is by using .catch() in
3 min read