Câu hỏi phỏng vấn Nodejs
Câu hỏi

What are async functions in ...

Câu trả lời

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.

Understanding Async Functions

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.

Key Characteristics:

  • Always returns a promise: Regardless of what the async function returns, it will always be wrapped in a promise[1][2][3].
  • Await keyword: The 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].
  • Error handling: Async functions make error handling straightforward with try/catch blocks, unlike the complex chaining of .then() and .catch() methods in traditional promise-based approaches[1][2][3].

Examples of Async Functions in Node.js

Here are a few examples to illustrate how async functions can be used in Node.js:

Example 1: Reading a File Asynchronously

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.

Example 2: API Request Handling

const axios = require('axios');

async function getUser(userId) {
    try {
        const response = await axio...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

What is the purpose of pm2 save ?

junior

What are the key features of Node.js?

senior

Why to use Buffer instead of binary string to handle binary data ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào