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

← All JS Promise reference · async/await vs promises vs callbacks