creation
new Promise
Constructs a promise from an executor function that receives resolve and reject callbacks. Use it to adapt callback-based or event-based APIs into promises.
new Promise((resolve, reject) => { ... }) Parameters
| Parameter | Purpose |
|---|---|
| resolve(value) | Fulfills the promise; if value is a thenable, it is adopted |
| reject(reason) | Rejects the promise; conventionally pass an Error |
| executor throws | A synchronous throw inside the executor rejects the promise |
Examples
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
await delay(1000); Classic wrapper around a callback-based timer.
const readFile = path => new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => err ? reject(err) : resolve(data));
}); Promisify a Node-style callback API.
const p = new Promise((resolve, reject) => {
throw new Error('boom');
});
p.catch(e => console.log(e.message)); // 'boom' Synchronous throws in the executor are caught and become rejections.
Gotcha
Only the FIRST call to resolve or reject counts — later calls are silently ignored. Don't use new Promise around an existing promise (the 'promise constructor anti-pattern') — just return the existing promise.
Related
Promise.resolve
Returns a promise fulfilled with the given value, or — if the value is already a promise or thenable — the same/adopted promise. Handy for normalizing 'might be a promise' inputs.
Promise.reject
Returns a promise that is already rejected with the given reason. Useful for early-exit paths in functions that must always return a promise.
Promise.withResolvers
Creates a promise and exposes its resolve and reject callbacks alongside it, avoiding the need to capture them from a new Promise executor. Added in ES2024 for the 'deferred' pattern.
← All JS Promise reference · async/await vs promises vs callbacks