The Promise.resolve
static method can be used to wrap values into promises.
let resolved = Promise.resolve(2);
resolved.then(value => {
// immediately invoked
// value === 2
});
If value
is already a promise, Promise.resolve
simply recasts it.
let one = new Promise(resolve => setTimeout(() => resolve(2), 1000));
let 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.
let resolved = Promise.resolve({
then(onResolved) {
onResolved(2);
}
});
resolved.then(value => {
// immediately invoked
// value === 2
});
The Promise.reject
static method returns a promise which immediately rejects with the given reason
.
let rejected = Promise.reject("Oops!");
rejected.catch(reason => {
// immediately invoked
// reason === "Oops!"
});