Promise.resolve()
The promise.resolve () method returns a Promise object. The returned Promise object depends on the value passed in as the following:
- parameter
value
isPromise object
, the input parameter is returned directlyPromise object
; - parameter
value
isthenable
(object with then method), then returnsPromise object
Depends on the execution of the THEN method; - parameter
value
If it is any other value, this value is returned directly as the resultfulfilled
The state of thePromise object
;
The input parameter is a Promise object
Let’s take a look at a few š° :
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(p1);
p1 === p2; // true
p2; // PromiseĀ {<fulfilled>: 1}
Copy the code
const p1 = Promise.reject(1);
const p2 = Promise.resolve(p1);
p1 === p2; // true
p2; // PromiseĀ {<rejected>: 1}
Copy the code
Whether the Promise object is a pity state or the Rejected state will not be affected. When the input parameter is a Promise object, the Promise object will be directly returned as the return value
The is thenable refs
Let’s start with a few š°
const thenable = {
then: () => {
}
};
const p = Promise.resolve(thenable);
p; // PromiseĀ {<pending>}
Copy the code
const thenable = { then: (resolve, reject) => { resolve('fulfilled! '); }}; const p = Promise.resolve(thenable); p; // Promise {<fulfilled>: "fulfilled!" }Copy the code
const thenable = { then: (resolve, reject) => { reject('rejected'); }}; const p = Promise.resolve(thenable); p; // Promise {<rejected>: "rejected"}Copy the code
const thenable = {
then: (resolve, reject) => {
throw new Error('123')
}
};
const p = Promise.resolve(thenable);
p; // PromiseĀ {<rejected>: Error: 123}
Copy the code
In fact, we can simply understand that when the input parameter is Thenable, the returned Promise object is the result of the new Promise() instantiation by passing the then function in thenable as an argument.
If you think about it more deeply, the above statement is not very strict.
- Promise. Resolve specification
- Further Promise
Promise.reject()
Resolve, promise.reject is simpler than promise.resolve, promise.reject. The state of the Promise object must be Rejected, and the result value is the value of the input parameter.
To name a few š° :
const p1 = Promise.resolve(1);
const p2 = Promise.reject(p1);
p1 === p2; // false
p2; // PromiseĀ {<rejected>: Promise}
Copy the code
const thenable = {
then: () => {}
};
const p = Promise.reject(thenable);
p; // PromiseĀ {<rejected>: {then: () => {}}}
Copy the code
const p = Promise.reject(1);
p; // PromiseĀ {<rejected>: 1}
Copy the code
conclusion
There is no epilogue to this issue.