The prototype approach
Promise.prototype.then
Promise.prototype.catch
Both methods are written in JS personal learning, A Promise implementation that conforms to the A+ specification. Including the following resolvePromise methods are written here.
Promise.prototype.finally
Finally returns a new Promise instance with the same state as the last promise instance. Finally returns a promise instance with the same state as the last promise instance.
Principle:
The finally method is essentially a complement to a normal THEN method that takes two arguments. The only difference is that finally returns a promise instance that is in the same state as the one that called it. The state of a promise instance returned by using then may not be the same as the state of the promise instance called:
var promise1 = new Promise((resolve, reject) => {
reject('error')
})
var promise2 = promise1.then(res => {
}, reason => {
})
setTImeout(() => {
console.log(promise1) // Promise{<rejected>: 'error'}
console.log(promise2) // Promise{<fulfilled>: undefined}
})
var promise1 = new Promise((resolve, reject) => {
reject('error')
})
var promise2 = promise1.finally(() => {
})
setTimeout(() => {
console.log(promise1) // Promise{<rejected>: 'error'}
console.log(promise2) // Promise{<rejected>: 'error'}
})
Copy the code
We can see some of the differences between using finally and THEN, so when finally is implemented, we simply simulate a normal chain call to then, complete its two parameters, and then return a new instance based on the state of the previous Promise instance.
Simply put, one method is executed in finally, and everything else remains the same as the previous Promise instance.
Promise.resolve('success').then(res => {return res}).finally(() => {// callback content}) // finally .then(value => {return promise.resolve ().then(() => {return value})}, reason => { retutn Promise.resolve().then(() => { throw reason }) })Copy the code
Implementation:
// finally accepts only one callback function, So you can just pass a callback Promise. The prototype. The finally = function (the callback) {return this. Then ((value) = > {/ * * */ return promise.resolve (callback()).then() => { return value; }); }, (err) => { return Promise.resolve(callback()).then(() => { throw err; }); }); }Copy the code
Method on an object
Promise.resolve()
The promise.resolve (value) method returns a Promise object resolved with the given value.
- If value is a Thenable object, the returned promise state is the same as thenable’s state.
- If the value itself is a Promise object, it is returned intact.
- In other cases, a promise object with a success status is returned directly.
Implementation:
If (value instanceof Promise) {return value} return new Promise((resolve, Reject) => {if (value && value.then && typeof value.then === 'function') {// Use setTimeout to ensure x. hen is executed asynchronously SetTimeout (() => {x. hen(resolve, reject)})} else {// resolve(value)}}Copy the code
Promise.reject()
The promise.reject () method differs from promise.resolve () in that you simply place the arguments in reject as arguments to subsequent methods.
Implementation:
Reject = function (reject) {return new Promise((reject, resolve); reject) => { reject(reason) }) }Copy the code
Promise.all()
Promise.all() takes an array of Promise instances and returns them wrapped as a new Promise instance. Success and failure return different values, with success returning an array of results and failure returning the reject value first.
Usage:
var p1 = new Promise((resolve, reject) => { resolve('success1') })
var p2 = new Promise((resolve, reject) => { resolve('success2') })
var p3 = Promise.resolve('success3')
var result = Promise.all([p1, p2, p3])
console.log(result) // Promise {<fulfilled>: Arrary(3)}
Copy the code
var p1 = new Promise((resolve, reject) => { resolve('success1') })
var p2 = new Promise((resolve, reject) => { reject('error2') })
var p3 = Promise.resolve('success3')
var result = Promise.all([p1, p2, p3])
console.log(result) // Promise {<reject>: 'error2'}
Copy the code
Other notes:
- If the argument passed in is an empty iterable, the promise callback completes (resolve), in which case it is executed synchronously, in all other cases asynchronously.
- Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises: Promises
- Promise. All is executed when all promises in promises are executed or when the state is’ Rejected ‘
- Promise. All returns a promise object in the state of ‘Rejected’ and the result is reason. If promises fail, promise. Promises are the first return value from the ‘Rejected’ state
- Promise.all returns an array in the same order as the promises passed in.
Implementation:
Promise. All = function (Promise) {// return new Promise((resolve, resolve, Promise) Reject) => {var index = 0 var result = [] var result = []; If (promises. Length === 0) {return resolve(result)} // If (promises. Length === 0) {return resolve(result)} For (let I = 0; for (let I = 0; i < promises.length; Resolve (Promise [I]). Then (value => {/**) Result [I] is used to store values to ensure that the order of returned results is the same as the order of the incoming promise, corresponding to case 5, because the call to then is asynchronous, in order to prevent the order of returned results in asynchronous state. Reslut.push (value) */ result[I] = value Resolve if (++index == promises. Length) {resolve(result)}}, Promis => promis => promis => promis => promis => promis => promis => promis => promis => promis => promis => promis => promis => promis => promis Therefore, it is not necessary to determine whether all promises succeed in the same way that success is determined above.Copy the code
Test code:
var promise1 = new Promise((resolve, reject) => {
resolve('success1')
})
var promise2 = 66;
var promise3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'success2')
})
Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values)
},(err)=>{
console.log(err)
});
var p = Promise.all([])
var p2 = Promise.all([2021, "wyt"])
console.log(p)
console.log(p2)
setTimeout(function(){
console.log('hello world')
console.log(p2)
})
Copy the code
Promise.race()
Promise.race() and promise.all () pass in an array as parameters and return a Promise object, but its state is determined by the Promise state fulfilled by the first implementation, whether this is a pity or rejected.
Usage:
var p1 = new Promise((resolve, reject) => { resolve('success1') })
var p2 = new Promise((resolve, reject) => { resolve('success2') })
var p3 = Promise.resolve('success3')
var result = Promise.race([p1, p2, p3])
console.log(result) // Promise {<fulfilled>: 1}
Copy the code
Implementation:
// Race is easier to implement than All. There is no need to judge whether promises are fully implemented. Promise.race = function (promises) { return new Promise((resolve, reject) => { for (let i = 0; i < promises.length; i++) { if (promises.length === 0) { resolve(promises) } Promise.resolve(promises[i]).then(value => { resolve(value) }, reason => { reject(reason) }) } }) }Copy the code
Promise.allSettled()
The promise.allSettled () method returns a Promise after all the given promises have fulfilled or rejected, with an array of objects each representing the corresponding Promise result.
Implementation:
The promise.allsettled () method is almost the same as promise.all (), Promise. AllSettled = function (Promise) {return new Promise((resolve, resolve, Promise) reject) => { var index = 0 var result = [] if (promises.length === 0) { return resolve(result) } for (let i = 0; i < promises.length; I ++) {Promise. Resolve (Promise [I]). Then (value => {// 'fulfilled', value: value } if (++index == promises.length) { resolve(result) } }, reason => { result[i] = { state: 'rejected', reason: If (++index == promises. Length) {reject(reason)}})}})} if (++index == promises.Copy the code
Promise.any()
The promise.any () method is the opposite of the promise.all () method, which returns the status and result of any Promise that is in a successful state
Implementation:
Promise.any = function (promises) { return new Promise((resolve, reject) => { var index = 0 var result = [] if (promises.length === 0) { return resolve(result) } for (let i = 0; i < promises.length; I ++) {Promise. Resolve (Promise [I]). Then (value => {// Resolve (value)}, reason => {result[I] = reason // Reject determines whether all reject is executed, If (++index == promises. Length) {reject(new Error('All promises were rejected')}})})}Copy the code