Using async/await
in Node.js allows you to write asynchronous code in a more synchronous-looking style, making it easier to understand and maintain. Here's a basic overview of how to use async/await
in Node.js:
Declare an asynchronous function:
Create an asynchronous function using the async
keyword before the function declaration.
javascriptasync function myAsyncFunction() {
// Asynchronous code here
}
Use await
inside the async function:
Inside the asynchronous function, use the await
keyword before any asynchronous operation (e.g., a function that returns a Promise).
javascriptasync function myAsyncFunction() {
const result = await someAsyncFunction();
// Do something with the result
}
Handling errors:
To handle errors in asynchronous functions, use try
and catch
blocks.
javascriptasync function myAsyncFunction() {
try {
const result = await someAsyncFunction();
// Do something with the result
} catch (error) {
// Handle the error
console.error('Error:', error);
}
}
If an error occurs in the asynchronous operation, it will be caught in the catch
block.
Example with a Promise:
Here's an example of using async/await
with a Promise in a simple Node.js script:
javascriptfunction wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function myAsyncFunction() {
console.log('Start');
try {
await wait(2000); // Wait for 2 seconds
console.log('After waiting');
} catch (error) {
console.error('Error:', error);
}
console.log('End');
}
myAsyncFunction();
In this example, wait
returns a Promise that resolves after a specified number of milliseconds. The myAsyncFunction
uses await
to wait for the Promise to resolve before moving on to the next statement.
Remember to run your Node.js script using a version of Node.js that supports async/await
(Node.js 8.0.0 and later). If you are using an older version, consider upgrading to a more recent one.