How to create a custom Promise in JavaScript
· Category: JavaScript
Short answer
Use the new Promise((resolve, reject) => { ... }) constructor to wrap callback-based or event-based code into a standardized Promise.
Steps
- Wrap a callback API:
javascript function readFilePromise(path) { return new Promise((resolve, reject) => { fs.readFile(path, "utf8", (err, data) => { if (err) reject(err); else resolve(data); }); }); } - Wrap a timeout:
javascript function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } await delay(500); - Convert an event to a Promise:
javascript function waitForEvent(el, name) { return new Promise(resolve => { el.addEventListener(name, resolve, { once: true }); }); }
Tips
- Always call
resolveorrejectexactly once. - Avoid mixing Promise constructors with existing Promise chains.
Common issues
- Creating a Promise but never resolving or rejecting it causes an indefinite hang.
- Synchronous throws inside a Promise constructor are not caught; wrap in try/catch and call
reject.