ES6 Promise object usage summary


Promise is used to deliver messages of asynchronous operations, and the Promise object represents an asynchronous operation.

features

1. The state of a Promise object is not affected by the outside world, that is to say, only the result of an asynchronous operation can change its state, and other operations cannot change this state; there are three states in total:

  1. pending (waiting): the initial state, not a success or failure state.
  2. fulfilled: means the operation completed successfully.
  3. rejected (refused): means that the operation failed.

2. There are only two possibilities for changing the state: pending→fulfilled and pending→rejected; once the state changes, it will not change again.

create

To create a promise object, you can use new to call the Promise constructor to instantiate:

var promise = new Promise(function(resolve, reject) {
    
    
    // 异步处理
    // 处理结束后、调用resolve 或 reject
});

The Promise constructor takes one parameter and a callback with two parameters resolve (resolve) and reject (reject). In the callback do something (e.g. async) and call resolve if everything is ok, otherwise call reject.
You can understand it by looking at the actual example.

practical example

function get(url, params = {
    
    }) {
    
    
    return new Promise((resolve, reject) => {
    
    
        axios.get(url, {
    
    
            params: params
        })
            .then(response => {
    
    
                resolve(response.data);
            })
            .catch(err => {
    
    
                reject(err)
            })
    })
}

Here, a promise object is first constructed, and the asynchronous method is to use axios to access the background information. The axios.get method may succeed in access (return normal information), or fail in access (return exception information). At this time, whether it is success or failure, we want to pass the information out. Therefore, if the access is successful, use the resolve method to pass out the successful information, and if the access fails, use the reject method to pass out the failed information. The parameters accepted by these two methods can be any value (of course, you can also pass no parameters).
The promise.then() method can be called for the promise object that has been instantiated, and the resolve and reject methods are passed as callbacks.
promise.then() is the most commonly used method of promises.

promise.then(onFulfilled, onRejected)

Promise simplifies the handling of errors. We can also write the above code like this:

promise.then(onFulfilled).catch(onRejected)

The next step is to call the get method:

get(xxxx,{
    
    })
	.then(result => {
    
     do something })
	.catch(err=> {
    
     do something });

Here, calling the get method gets a Promise object, and then calls the then method, where the result is the response.data passed in resolve(response.data); and calling the catch method, err is the err passed in reject(err) .

Promise.resolve method, Promise.reject method

To convert an existing object into a Promise object, you can use the Promise.resolve method or the Promise.reject method:

Promise.resolve('fyk').then(function(value){
    
    
    console.log(value); // 打印出fyk
});

The Promise object transformed by resolve directly enters the fulfilled (completed) state;

Promise.reject('fyk').catch(function(error){
    
    
    console.log(error);// 打印出fyk
});

The Promise object transformed by reject directly enters the rejected (rejected) state;

Guess you like

Origin blog.csdn.net/fyk844645164/article/details/100551016