Promisifying values

suggest change

The Promise.resolve static method can be used to wrap values into promises.

const resolved = Promise.resolve(2);
resolved.then(value => {
    // queued as a microtask, not run synchronously
    // value === 2
});

If value is already a native promise, Promise.resolve returns that same promise.

const one = new Promise(resolve => setTimeout(() => resolve(2), 1000));
const two = Promise.resolve(one);
two.then(value => {
    // 1 second has passed
    // value === 2
});

In fact, value can be any “thenable” (object defining a then method that works sufficiently like a spec-compliant promise). This allows Promise.resolve to convert untrusted 3rd-party objects into trusted 1st-party Promises.

const resolved = Promise.resolve({
    then(onResolved) {
        onResolved(2);
    }
});
resolved.then(value => {
    // queued as a microtask
    // value === 2
});

The Promise.reject static method returns a promise which immediately rejects with the given reason.

const rejected = Promise.reject("Oops!");
rejected.catch(reason => {
    // queued as a microtask
    // reason === "Oops!"
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents