FrontendInterviews.dev

Loading problem…

86. Promise.resolve and Promise.reject Polyfill

Medium•

Implement Promise.resolve and Promise.reject static methods that create resolved and rejected promises.

These static methods are essential utilities for working with Promises:

  • Promise.resolve(value): Creates a resolved promise with the given value
  • Promise.reject(reason): Creates a rejected promise with the given reason

Requirements

1. Promise.resolve

  • Accept any value (promise, thenable, or plain value)
  • Return a promise that resolves with the value
  • If value is a promise, return it as-is
  • If value is a thenable, follow the thenable
  • If value is plain, wrap it in a resolved promise

2. Promise.reject

  • Accept any rejection reason
  • Return a promise that rejects with the reason
  • Always reject (even if reason is a promise)

3. Edge Cases

  • Handle null/undefined values
  • Handle already settled promises
  • Handle thenables (objects with then method)

Example Usage

// Promise.resolve
Promise.resolve(42).then(console.log); // 42
Promise.resolve(Promise.resolve(1)).then(console.log); // 1

// Promise.reject
Promise.reject('error').catch(console.log); // 'error'
Promise.reject(new Error('fail')).catch(err => err.message); // 'fail'

// Thenable handling
const thenable = { then: (resolve) => resolve('thenable') };
Promise.resolve(thenable).then(console.log); // 'thenable'

Constraints

  • Promise.resolve must handle promises, thenables, and plain values
  • Promise.reject must always reject with the given reason
  • Must return a Promise instance
  • Must handle edge cases (null, undefined, already settled promises)
Accepted15/19|Acceptance Rate78.9%