What does Promisifying technique mean in Node.js?
What does Promisifying technique mean in Node.js?
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."
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.
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));
.catch()
[1][2][3].While util.promisify()
is powerful, it works b...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào