pass a callback funcion into an async function node js
To pass a callback function into an async function in Node.js, you can follow these steps:
Define an async function: Start by defining an async function using the
async
keyword. This function will perform some asynchronous operation and return a promise.Add a callback parameter: In the function signature, include a parameter for the callback function. This parameter will be used to pass the result or error to the caller.
Perform the asynchronous operation: Inside the async function, perform the desired asynchronous operation. This could be reading from a file, making an HTTP request, or any other asynchronous task.
Handle the result: Once the asynchronous operation is complete, handle the result or error. If the operation was successful, call the callback function with the result as the argument. If there was an error, call the callback function with the error as the argument.
Returning a promise: The async function should return a promise that resolves to the result or rejects with the error. This allows the caller to handle the asynchronous operation using
async/await
or.then()
and.catch()
.
Here is an example:
async function fetchData(callback) {
try {
// Perform asynchronous operation, e.g., fetching data from an API
const data = await fetch('https://api.example.com/data');
// Call the callback function with the result
callback(null, data);
} catch (error) {
// Call the callback function with the error
callback(error);
}
}
// Usage:
fetchData((error, data) => {
if (error) {
console.error('Error:', error);
} else {
console.log('Data:', data);
}
});
In this example, the fetchData
function is defined as an async function. It performs an asynchronous operation by fetching data from an API. The result or error is passed to the callback function provided as an argument. The caller can handle the result or error accordingly.