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

What does Promisifying technique mean in Node.js?

Câu trả lời

In Node.js, the term "promisifying" refers to the technique of converting a function that uses the traditional callback-based approach into one that returns a Promise. This transformation is particularly useful in asynchronous programming, allowing developers to write cleaner, more manageable code by avoiding the complexities often associated with nested callbacks, commonly known as "callback hell."

Understanding Promisification

Promisification wraps an asynchronous function that accepts a callback into a new function that returns a Promise. This promise resolves when the asynchronous operation completes successfully and rejects if an error occurs.

How Promisification Works

Node.js provides a built-in utility method called util.promisify() for converting callback-based functions to promise-based ones. This method takes a function following the Node.js convention (error-first callbacks) as an argument and returns a new function that returns a Promise[1][2][3][6][10][13].

Here’s a basic example of how to use util.promisify():

const util = require('util');
const fs = require('fs');

// Convert the callback-based version of readFile into a promise-based version
const readFilePromise = util.promisify(fs.readFile);

readFilePromise('./example.txt', 'utf8')
  .then(data => console.log(data))
  .catch(error => console.error(error));

Benefits of Promisification

  1. Improved Error Handling: Promises simplify error handling, allowing developers to handle errors at any point in the promise chain using .catch()[1][2][3].
  2. Cleaner Code: By using promises, developers can avoid deeply nested structures and make their code more readable and maintainable[1][2][3].
  3. Better Control Flow: Promises provide better control over asynchronous flows, making it easier to perform sequences of asynchronous operations[1][2][3].

Limitations and Considerations

While util.promisify() is powerful, it works b...

junior

junior

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

middle

What is the relationship between Node.js and V8?

senior

How would you handle errors for async code in Node.js?

senior

Is Node.js entirely based on a single-thread?

Bình luận

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

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