ES6 Promise basic knowledge summary

This article mainly refers to Ruan Yifeng's introduction to ECMAScript 6

1. What is Promise?

1. Meaning: Promise represents the result of asynchronous operation and is a solution for asynchronous programming; it can also be understood as a container that stores the result of the event (asynchronous operation) to be executed; in terms of syntax, Promise is an object , Through which you can get the news of asynchronous operation.
2. Purpose: To avoid the hell callback problem caused by function callbacks and events; Promise provides a unified API that can make asynchronous operations easier.
3. Status: pending (in progress), fulfilled / resolved (successful), rejected (failed).
4. Features: The state of the Promise object is not affected by the outside world; once the Promise state changes, it will not change again (from pending to fulfilled or from pending to rejected).
5. Disadvantages: Once the Promise is created, it will be executed immediately and cannot be cancelled in the middle; if the callback function is not set, the error inside the promise will not be reflected to the outside; the progress of the promise cannot be monitored during pending
6. Basic usage: The Promise object is a constructor, Used to generate Promise instances.

let promise = new Promise(resolve,reject){
    
    
	if(success){
    
    
		resolve(value);
	}else{
    
    
		reject(error);
	}
}

The Promise constructor accepts a function as a parameter, and the two parameters of the function are resolve and reject.

The role of the resolve function is to change the state of the Promise object from "unfinished" to "successful" (that is, from pending to resolved), called when the asynchronous operation succeeds, and pass the result of the asynchronous operation as a parameter;
The function of reject is to change the state of the Promise object from "unfinished" to "failed" (that is, from pending to rejected), called when the asynchronous operation fails, and the error reported by the asynchronous operation is passed as a parameter .

Second, the method

1、Promise.prototype.then()

The then method is defined on the prototype object Promise.prototype. Its role is to add a callback function when the state of the Promise instance changes. The first parameter of the then method is the callback function in the resolved state, and the second parameter (optional) is the callback function in the rejected state.

let promise = new Promise(function(resolve,reject){
    
    
	resolve('success');
})
promise.then(res=>{
    
    
	console.log(res);
},err=>{
    
    
	console.log(err);
})

The then method returns a new Promise instance (note, not the original Promise instance). Therefore, chain writing can be used, that is, another then method is called after the then method.

let promise = new Promise(function(resolve,reject){
    
    
	resolve('success');
})
promise.then(res=>{
    
    
	console.log(res);
	return 'second';
}).then(res=>{
    
    
	console.log(res);
})
//success second

The above method specifies two then callback functions. After the first function is completed, the return value will be passed to the second function as a parameter.

The callback function specified by the first then method returns another Promise object. At this time, the callback function specified by the second then method will wait for the state of this new Promise object to change.

const prom= new Promise(function(resolve,reject){
    
    
	resolve('success');
})
prom.then(function(res){
    
    
	console.log(res);
	return new Promise((resolve, reject) => {
    
    
     setTimeout(() => {
    
    
       resolve(2);
     }, 1000);
   })
}).then(res=>{
    
    
	console.log(res);
})
//success 2
2、Promise.prototype.catch()

Used to specify the callback function when an error occurs; a Promise is returned.

let promise = new Promise(function(resolve,reject){
    
    
	reject('error');
})
promise.then(res=>{
    
    
	console.log(res);
}).catch(err=>{
    
    
	console.log(err);
})
// error

The above Promise execution state is resolved, then the callback function specified by then will be called, if it is rejected, the callback function specified by catch will be called; the catch() method can also capture errors in the then() method.

The error of the Promise object has a "bubble nature" and will be passed to the back until it is caught. Therefore, it is recommended to use the catch() method to catch errors instead of the second parameter of the then() method.

let promise = new Promise(function(resolve,reject){
    
    
	resolve('success');
})
promise.then(res=>{
    
    
	console.log(res);
	return new Promise(function(resolve,reject){
    
    
		reject('err1');
	})
}).then(res=>{
    
    
	console.log(res)
}).catch(err=>{
    
    
	//这里会处理上面所有Promise产生的错误
})
// success err1

If the Promise status has become resolved, throwing an error again is invalid.

let promise = new Promise(function(resolve,reject){
    
    
	resolve('success');
	reject(new Error('error'));
})
promise.then(res=>{
    
    
	console.log(res);
}).catch(err=>{
    
    
	console.log(err);
})
// success

The catch() method returns a Promise object, so you can call the then() method later.

let promise = new Promise(function(resolve,reject){
    
    
	reject(new Error('error'));
})
promise.then(res=>{
    
    
	console.log(res);
}).catch(err=>{
    
    
	console.log(err);
	return '2';
}).then(res=>{
    
    
	console.log(res);
})
// Error: error  2

In the above code, if no error is reported, the catch() method will be skipped and the then() method below will be executed directly.

In the catch() method, errors can be thrown again.

let promise = new Promise(function(resolve,reject){
    
    
	reject(new Error('error'));
})
promise.then(res=>{
    
    
	console.log(res);
}).catch(err=>{
    
    
	console.log(err);
	return new Promise((resolve,reject)=>{
    
    
		reject(new Error('this is a error'))
	});
}).catch(err=>{
    
    
	console.log(err);
})
// Error: error  Error: this is a error
3、Promise.prototype.finally()

finally() returns a Promise, the method is used to specify the operation that will be executed regardless of the final state of the Promise object. This method is introduced into the standard by ES2018.

var promise = Promise.resolve('success')
.then(res=>{
    
    
	console.log(res);
})
.catch(err=>{
    
    
	console.log(err);
})
.finally(()=>{
    
    
	console.log('finally');
})
//success finally

Regardless of the final state of the promise, after the callback function specified by then or catch is executed, the callback function specified by the finally method will be executed.

After finally, you can continue then, and the value will be passed to the subsequent then intact;

var promise = Promise.resolve('success')
  .finally(() => {
    
     
    return '1';
  })
  .then(res=> {
    
    
    console.log(res);
  }).catch(err=>{
    
    
	console.log(err);
  });
  //success

Finally, it has limited influence on the resolution of the promise returned by itself. It can change the previous resolve to reject, or change the previous reject to another reject, but it cannot change the previous reject to resolve.

var promise = Promise.resolve('success')
  .finally(() => {
    
     
    return Promise.reject('this is a error') 
  })
  .then(res=> {
    
    
    console.log(res)
  }).catch(err=>{
    
    
	console.log(err)
  });
  //this is a error
4、Promise.all()

This method wraps multiple Promise instances into a new Promise instance.

const p = Promise.all([p1, p2, p3]);

The Promise.all() method receives an array as a parameter, and p1, p2, and p3 are all Promise instances. If not, the Promise.resolve() method will be called to convert the parameters to the Promise instance for processing;
compare the above case:
(1) Only p1 The states of, p2 and p3 all become resolved, and the state of p will become resolved. At this time, the return values ​​of p1, p2, and p3 form an array, which is passed to the callback function of p.
(2) As long as one of p1, p2, and p3 is rejected, the status of p becomes rejected. At this time, the return value of the first rejected instance will be passed to the callback function of p.

const p1 = new Promise((resolve, reject) => {
    
    
  resolve('hello');
})
.then(res => res)
.catch(err => err);

const p2 = new Promise((resolve, reject) => {
    
    
  reject(new Error('报错了'));
})
.then(res => res)
.catch(err => err);

Promise.all([p1, p2])
.then(res => console.log(res))
.catch(err => console.log(err));
// ["hello", Error: 报错了]

In the above code, p1 is resolved, p2 is rejected, but because p2 has its own catch method, this method returns a new Promise instance, and p2 actually points to this instance. The instance will become resolved after the catch method is executed, so Promise .all() Both parameters return resolved, so the callback function specified by the then method will be called.

const p1 = new Promise((resolve, reject) => {
    
    
  resolve('hello');
})

const p2 = new Promise((resolve, reject) => {
    
    
  reject(new Error('报错了'));
})

Promise.all([p1, p2])
.then(res => console.log(res))
.catch(err => console.log(err));
//Error: 报错了

The above code p2 has no catch method, so the catch method of Promise.all() will be used.

5、Promise.race()

Like Promise.all(), wrap multiple Promise instances into a new Promise instance.

const p = Promise.race([p1, p2, p3]);

The Promise.race() method receives arrays as parameters, p1, p2, and p3 are all Promise instances, if not, the Promise.resolve() method will be called to convert the parameters to Promise instances for processing;
compare the above case: as long as p1, p2, One instance in p3 changes state first, and the state of p changes accordingly. The return value of the Promise instance that changes first is passed to the callback function of p.

const p1 = new Promise((resolve, reject) => {
    
    
  resolve('hello');
})

const p2 = new Promise((resolve, reject) => {
    
    
  reject(new Error('报错了'));
})

Promise.race([p1, p2])
.then(res => console.log(res))
.catch(err => console.log(err));
		// "hello"
6 、 Promise.allSettled ()

This method accepts a set of Promise instances as parameters and wraps them into a new Promise instance. Only when all these parameter instances return results, whether fulfilled or rejected, the packaging instance will end. This method was introduced by ES2020.

const p1 = new Promise((resolve, reject) => {
    
    
  resolve('hello');
})

const p2 = new Promise((resolve, reject) => {
    
    
  reject(new Error('报错了'));
})

Promise.allSettled([p1, p2])
.then(res => console.log(res))
//[
//  {status:'fulfilled',value:'hello'},
//	{status:'rejected',reason:Error:报错了}
//]

This method returns a new Promise instance. Once it ends, the status will always be fulfilled and will not become rejected; it will return an array with the final running results of all parameters

7、Promise.any()

ES2021 introduced the Promise.any() method. This method accepts a set of Promise instances as parameters and wraps them into a new Promise instance to return. As long as one of the parameter instances becomes the fulfilled state, the package instance will become the fulfilled state (the return value is the return value of the first instance in the fulfilled state); if all the parameter instances become the rejected state, the package instance will become rejected state.

const p1 = new Promise((resolve, reject) => {
    
    
  resolve('hello');
})

const p2 = new Promise((resolve, reject) => {
    
    
  resolve('你好');
})

Promise.any([p2, p1])
.then(res => console.log(res))
.catch(err=>{
    
    console.log(err)})
//hello

The Promise.any() method is very similar to the Promise.race() method, except that it does not end because a certain Promise becomes rejected.

The error thrown by Promise.any() is not a general error, but an instance of AggregateError.

const p1 = new Promise((resolve, reject) => {
    
    
  reject(new Error('报错了'));
})

const p2 = new Promise((resolve, reject) => {
    
    
  reject(new Error('报错了'));
})

Promise.any([p2, p1])
.then(res => console.log(res))
.catch(err=>{
    
    console.log(err)})
//AggregateError: All promises were rejected
8、Promise.resolve()

Sometimes it is necessary to convert an existing object into a Promise object, and the Promise.resolve() method plays this role.

Promise.resolve('hello');
//等价于
new Promise(resolve => resolve('hello'))
//hello

Promise.resolve() returns the resolved Promise instance according to the parameters; if it is a Promise, it returns intact; the parameter is a thenable object (with a then method), it will convert this object into a Promise, and then immediately execute then; the parameter has no then The method may be empty and return a Promise object in the resolved state;

9、Promise.reject()

This method will also return a new Promise instance whose status is rejected.

Promise.reject('出错了');
//等价于
new Promise(reject=> reject('出错了'))
//出错了

The parameters of the Promise.reject() method will be used as the reason for rejection intact and become the parameters of the subsequent method.

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/111506615