Write a Node.js function to handle asynchronous operations using async/await.
Write a Node.js function to handle asynchronous operations using async/await.
32426-Jul-2023
Updated on 27-Jul-2023
Home / DeveloperSection / Forums / Write a Node.js function to handle asynchronous operations using async/await.
Write a Node.js function to handle asynchronous operations using async/await.
Aryan Kumar
27-Jul-2023Sure, here is an example of a Node.js function to handle asynchronous operations using async/await:
JavaScript
This function first imports the
fs
module, which provides access to the file system. The function then defines an async function calledhandleAsyncOperations()
. ThehandleAsyncOperations()
function uses theawait
keyword to wait for the results of thefs.readFile()
asynchronous operations.The
fs.readFile()
method returns a promise, which is a special object that represents the eventual result of an asynchronous operation. Theawait
keyword can be used to wait for the promise to resolve, and then the result of the promise is assigned to the variable.In this example, the
handleAsyncOperations()
function first reads the filedata1.txt
and then reads the filedata2.txt
. The results of the two read operations are then logged to the console.To run this function, you can save it as a file called
handleAsyncOperations.js
and then run it from the command line:This will run the
handleAsyncOperations()
function and log the contents of the two files to the console.