SyntaxStudy
Sign Up
JavaScript Intermediate 4 min read

Creating Promises

Creating Promises

Wrap callback-based APIs with the Promise constructor to make them thenable.

Example
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);
Pro Tip

In Node, prefer util.promisify or the built-in fs.promises to manual wrapping.