Async/await is a feature in Node.js (and JavaScript in general) that allows you to write asynchronous code in a more "synchronous-looking" manner. This can make your code less cluttered and easier to read, especially in larger projects.
To use async/await, you need to be familiar with Promises, as async/await is essentially a syntactic sugar over Promises to make handling them more straightforward.
Here’s an overview of how to use async/await in Node.js:
1. **Async functions**
To use ‘await‘, the function that contains it must be declared as ‘async‘. An ‘async‘ function always returns a Promise (if the function doesn’t return a Promise, it is automatically wrapped in one). The ‘async‘ keyword is used before the ‘function‘ keyword or an arrow function.
async function myAsyncFunction() {
// ...
}
const myAsyncArrowFunction = async () => {
// ...
};
2. **Await keyword**
Inside async functions, you can use the ‘await‘ keyword to "wait" for a Promise to resolve or reject. When an awaited Promise resolves, the function execution continues and the resolved value is returned. If the awaited Promise rejects, an error is thrown and you can catch it with a try-catch block. Remember, you can only use the ‘await‘ keyword inside an ‘async‘ function.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log('Data fetched:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
In this example, ‘fetchData‘ waits for the ‘fetch‘ function to resolve, then waits for the ‘response.json()‘ to resolve. If either of these Promises reject, the error is caught and logged.
3. **Error handling**
You can use try-catch blocks for error handling in async functions, as shown in previous example. Alternatively, you can handle errors by chaining a ‘.catch()‘ after an async function invocation. This is similar to handling errors in Promises:
async function fetchDataWithError() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log('Data fetched:', data);
}
fetchDataWithError()
.catch(error => console.error('Error fetching data:', error));
Keep in mind that while async/await makes the code look more synchronous, it is still asynchronous under the hood. Using async/await can help make your code cleaner and more readable, but you should still be aware of the asynchronous nature of your code to avoid common pitfalls, such as race conditions or deadlocks.