Creating Promises
Wrap callback-based APIs with the Promise constructor to make them thenable.
Wrap callback-based APIs with the Promise constructor to make them thenable.
function readFile(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, "utf8", (err, data) => err ? reject(err) : resolve(data));
});
}
// util.promisify does this automatically in Node
const { promisify } = require("util");
const readFileAsync = promisify(fs.readFile);
In Node, prefer util.promisify or the built-in fs.promises to manual wrapping.
More in JavaScript