Study notes-detailed explanation of Promise objects in ES6


There is an important object Promise in ES6, which can be used by new. Represents what will happen in the future and is used to describe the results of asynchronous operations. The function often includes asynchronous and time-consuming code.

1. Basic configuration of Promise:

{              挂起      成功        失败
    status: 'pending | fulfilled | rejected', // status最多只能变化一次
    // 状态的改变只有两种可能:pending -> fulfilled, pending -> rejected
    data: undefined,    // 需要携带的数据,没有默认undefined
    success: null,      // 成功的回调函数
    failure: null,      // 失败的回调函数
    then: function(fn, fn2) {
        this.success = fn;
        this.failure = fn2;
    },
    resolve: function(data) { 获取一个成功状态的promise
        this.data = data;
        this.status = "fulfilled";
    },
    reject: function(data) { 获取一个失败状态的promise
        this.data = data;
        this.status = "rejected";
    }
}

Advantages: Asynchronous code is represented by a synchronous process. Avoid hell callbacks (callback functions are nested in layers).

Disadvantages: It cannot be cancelled after creation, and a callback function must be set.

2. Creation of Promise object:

var p =  new Promise(function(resolve,reject) {
    setTimeout(function() {
        
    }, 2000);
}).then(function(data) => {})
  .catch(function(data) => {});

Catch is essentially a special then function (the first parameter is null, and the second parameter is a function). The then function and catch function of Promise always return a new promise object. In this way, we can continue the then, and the Promise stipulates: the return value of the previous then parameter function will be passed to the next parameter function as a parameter. If there is no indication in the then, a failed Promise or an exception occurs, the then function And the catch function always returns a successful Promise.

Promise.resolve(123).then(data => { console.log(data); return Promise.resolve(456) }) 
// data 123
                    .then(data => { console.log(data); return Promise.reject(789) })  
// data 456
                    .catch(data => { console.log(data); }) // data 789

 3. Methods in Promise (not used yet):

Promise.all([p1,p2,p3]) wraps multiple Promise instances into a new Promise object. The parameter does not have to be an array

The status of Promise.all([p1,p2,p3]) is divided into two cases:

Only when the states of p1, p2, and p3 all become fulfilled, will the state of p become fulfilled. At this time, the return values ​​of p1, p2, and p3 form an array, which is passed to the callback function of p.

As long as one of p1, p2, and p3 is rejected, the status of p becomes rejected, and the return value of the first rejected instance will be passed to the callback function of p.

// 第一种情况,全是成功状态
var p1 = new Promise((resolve, reject) => { let data = 10; resolve(data) });
var p2 = new Promise((resolve, reject) => { let data = 100; resolve(data) });
var p =  Promise.all([ p1, p2 ]);
p.then((datas) => { console.log(datas); });    // [10, 100]

// 第二种情况, 有一个是失败状态
var p1 = new Promise((resolve, reject) => { let data = 10; resolve(data) });
var p2 = new Promise((resolve, reject) => { let data = 100; reject(data) });
var p =  Promise.all([ p1, p2 ]);
p.then((datas) => { console.log(datas); }).catch((datas) => { console.log(datas); });// 100

The Promise.race method also wraps multiple Promise instances into a new Promise instance.

As long as the state of an object in Promise.race([p1,p2,p3]) changes first, its state will change accordingly. The return value of the Promise instance that changes first is passed to its return value.

And if the parameters of the Promise.all() and Promise.race() methods are not Promise objects, the Promise.resolve and Promise.reject methods will be called first.

var p1 = Promise.resolve('成功了');
p1.then(data => { console.log(data); }); 	// 成功了

var p1 = Promise.reject('失败了');
p1.then(null, data => { console.log(data); }); 	// 失败了

Promise objects are often used to describe asynchronous and time-consuming operations. We will also use Promise objects to encapsulate Ajax and some time-consuming asynchronous operations. Make the code more elegant.

Guess you like

Origin blog.csdn.net/qq_41339126/article/details/109398935
Recommended