What are async functions in ...
What are async functions in ...
Async functions in Node.js are a powerful feature that allows developers to write asynchronous code in a way that is cleaner and more readable than traditional callback-based approaches. These functions are built on top of JavaScript's Promise object and are designed to simplify the handling of asynchronous operations.
An async function in Node.js is declared with the async
keyword. It can contain zero or more await
expressions. Async functions always return a promise. If the function returns a value that is not explicitly a promise, it will be automatically wrapped in a promise. This feature enables the use of asynchronous code that appears synchronous, making it easier to understand and maintain.
await
keyword can only be used inside async functions. It pauses the function execution until the awaited promise resolves, which simplifies the handling of the promise[1][2][3]..then()
and .catch()
methods in traditional promise-based approaches[1][2][3].Here are a few examples to illustrate how async functions can be used in Node.js:
const fs = require('fs').promises;
async function readFile(filePath) {
try {
const data = await fs.readFile(filePath, 'utf8');
console.log(data);
} catch (error) {
console.error('Error reading file:', error);
}
}
readFile('./example.txt');
In this example, the readFile
function is declared with async
, and it uses await
to pause execution until fs.readFile
has completed. If the file read fails, the error is caught and logged.
const axios = require('axios');
async function getUser(userId) {
try {
const response = await axio...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào