Summary of Promise object methods

ECMAscript 6 natively provides Promise objects.

Promise

The Promise object represents an event that will occur in the future, and is used to transmit asynchronous operation messages. It is a set of asynchronous operation processing mechanism.

Promise objects solve the problem of nested callback hell.

The callback function of resolved state and rejected state are respectively formulated through the then method.

1. Promise features

  • It can handle errors flexibly in a series of asynchronous operations, avoiding nested callback functions.

Promises also have some disadvantages. First of all, the Promise cannot be cancelled. Once it is created, it will be executed immediately and cannot be cancelled halfway. Secondly, if the callback function is not set, the error thrown inside the Promise will not be reflected to the outside. Third, when it is in the Pending state, it is impossible to know which stage it is currently in (just started or is about to be completed).

Second, the creation of Promise

const promise = new Promise(function(resolve, reject) {
    
    
  // ... some code
 
  if (/* 异步操作成功 调用resolve */){
    
    
    resolve(value);
  } else {
    
    
    /* 异步操作失败 调用reject */
    reject(error);
  }
});

resolve: called when the asynchronous operation succeeds, and pass the result of the asynchronous operation as a parameter;

​ reject: called when the asynchronous operation fails, and the error reported by the asynchronous operation is passed as a parameter;

三、Promise.prototype.then()

After the Promise instance is generated, you can use the then method (then method is defined on the prototype object Promise.prototype . Its role is to add a callback function for the Promise instance when the state changes.), the catch method specifies the Resolved state and the Rejected state respectively Callback:

ew Promise(function(resolve,reject) {
    
    
    let num = Math.random() * 2;
    console.log("产生的随机数为:" + num);
    setTimeout(function () {
    
    
        if(num < 1) {
    
    
            console.log("执行成功");
            resolve("200 OK");
        } else {
    
    
            console.log("执行失败");
            reject("失败原因num为:" + num);
        }
    }, num * 1000);
}).then(function(r) {
    
    
    console.log("then:" + r);
}).catch(function(j) {
    
    
    console.log("catch:" + j);
});

四、Promise.prototype.catch()

The Promise.prototype.catch() method is used to specify the callback function when an error occurs.

const p1 = new Promise(function cb(resolve, reject) {
    
    
    setTimeout(() => {
    
    
        console.log('欢迎')
        reject()
    }, 3000)
})
p1.then(_ => {
    
    
    setTimeout(() => {
    
    
        console.log('谢谢光临')
    }, 2000)
}).catch(_ => {
    
    
    console.log('出错了')
})

When a promise throws an error, it is caught by the callback function specified by the catch() method.

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

五、Promise.prototype.finally()

The finally() method returns a Promise .
At the end of the promise, whether the result is fulfilled or rejected , the specified callback function will be executed. This provides a way for code that needs to be executed after the Promise is successfully completed.

This avoids the situation where the same statement needs to be written once in **then() and catch()**.

p.finally(onFinally);

p.finally(function() {
    
    
   // 返回状态为(resolved 或 rejected)
});

parameter:

  • onFinally
  • Function to be called after the Promise ends.

return value:

  • ​Returns a Promise object with a finally callback function.

六、Promise.all()

The Promise.all(iterable) method returns an instance. In this instance, all the promises in the iterable parameter are “resolved” or the parameter does not contain the promise, the callback is completed (resolve); if one of the promises in the parameter fails (rejected), This instance callback failed (reject), the reason for the failure is the result of the first failed promise.

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
    
    
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
    
    
  console.log(values);
});
// expected output: Array [3, 42, "foo"]

Reference boss: https://blog.csdn.net/m0_46532221/article/details/106528918

Guess you like

Origin blog.csdn.net/Menqq/article/details/111395911