Promise construction helpers
How it works
Promise.resolve converts a value or thenable to a promise; Promise.reject creates a rejected promise. Promise.withResolvers() returns a promise with its paired resolve and reject functions, useful when an external event controls completion. Promise.try() invokes a callback immediately and wraps its returned value or thrown exception in a promise. These newer methods require feature checks in older runtimes. Avoid extra promise constructors around APIs that already return promises.
Example 1
const {promise, resolve} = Promise.withResolvers();promise.then(console.log);resolve(12);Expected output in the tested environment:
12The resolver is available outside the constructor callback.
Example 2
if (typeof Promise.try === "function") { Promise.try(() => { console.log("call"); throw new Error("oops"); }).catch(e => console.log(e.message)); console.log("after");} else { console.log("Promise.try unavailable"); }Expected output in the tested environment:
Promise.try unavailableIn Node.js 22.16.0 only the fallback runs. On a supporting runtime the native branch prints call, after, then oops.
Common mistake
Promise.resolve(fn()) does not catch a synchronous exception from evaluating fn() before the resolve call. Promise.try(fn) handles that callback completion.
Practice
Implement an equivalent resolver pair using the Promise constructor, and compare it with withResolvers. Test for Promise.try availability before running its example.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Promise construction helpers — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
Which helper exposes a promise together with resolve and reject?
When is the callback of Promise.try(fn) invoked?
Why does Promise.resolve(fn()) not catch every error from fn?
For Promise construction helpers, what is the console output of example 1 in Node.js 22.16.0?
const {promise, resolve} = Promise.withResolvers();promise.then(console.log);resolve(12);For Promise construction helpers, what is the console output of example 2 in Node.js 22.16.0?
if (typeof Promise.try === "function") { Promise.try(() => { console.log("call"); throw new Error("oops"); }).catch(e => console.log(e.message)); console.log("after");} else { console.log("Promise.try unavailable"); }