instance method and static method of promise

promise overview

introduce

Promise is one of the important features of ES6

The traditional asynchronous programming solution is to use callback functions, but this will lead to deep nesting and callback hell, so another solution to promise asynchronous programming will be more powerful.

three states

  • pending ( pending ) initial state, neither honored nor rejected
  • fulfilled means the operation completed successfully
  • rejected ( rejected ) means that the operation failed.

features

  • Pending Promise objects are either fulfilled with a value or rejected with a reason (error) When one of these situations occurs, we line up the relevant processing with the promise's then method program will be called
  • Promise.prototype.thenand Promise.prototype.catchmethods return promises, so they can be chained

Three instance methods of promise

then() method

  • then is the callback function when the instance state changes, the first parameter is the callback function of the resolved state, and the second parameter is the callback function of the rejected state
  • The then method returns a new Promise instance, which is why promises can be written in chains
promise.then(result => {
    
    ···})

catch method

When an exception occurs, the catch method is required to capture it

promise.then(result => {
    
    ···}).catch(error => {
    
    ···})

finally() method

The method is used to specify the operation that will be performed regardless of the final state of the Promise object

promise.then(result => {
    
    ···}).catch(error => {
    
    ···}).finally(() => {
    
    ···});

static method of promise

resolve method

The method returns an object parsed with the given value. The given value has the following situations:Promise

  • If the value is a promise, then the promise will be returned
  • The parameter is not an object with a then() method, or is not an object at all, Promise.resolve() will return a new Promise object with a status of resolved
  • When there is no parameter, directly return a Promise object in resolved state

reject() method

The Promise.reject(reason) method also returns a new Promise instance whose status is rejected

const p = Promise.reject('出错了')

等同于
const p = new Promise((resolve, reject) => reject('出错了'))
p.then(null, function (s) {
    
    console.log(s)})
//出错了Promise.reject()方法的参数,会原封不动地变成后续方法的参数

any() method

Takes an Promiseiterable object, and as soon as one of them promisesucceeds , returns the one that has succeeded promise. If none of the iterable promisesucceeds (i.e. promisesall fail/reject), return promise an AggregateErrorinstance of the failed and type, which is a subclass Errorof and used to group single errors together. Essentially, this approach Promise.all()is the opposite.

const pErr = new Promise((resolve, reject) => {
    
    
  reject("总是失败");
});

const pSlow = new Promise((resolve, reject) => {
    
    
  setTimeout(resolve, 500, "最终完成");
});

const pFast = new Promise((resolve, reject) => {
    
    
  setTimeout(resolve, 100, "很快完成");
});

Promise.any([pErr, pSlow, pFast]).then((value) => {
    
    
  console.log(value);
  // pFast fulfils first
})

All() method

  1. The method receives the input of a promise iterable type (Note: Array, Map, and Set all belong to the ES6 iterable type) and returns only one Promiseinstance

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

    The state of instance p is determined by p1, p2, p3, which can be divided into two cases:

    1. Only when the states of p1, p2, and p3 become fulfilled, the state of p will become fulfilled. At this time, the return values ​​of p1, p2, and p3 form an array and pass it to the callback function of p.
    2. As long as one of p1, p2, and p3 is rejected, the state of p becomes rejected, and the return value of the first rejected instance will be passed to the callback function of p

allSettled method

Promise.all will enter the failed state when any request fails

Since a single Promise enters the rejected state, the result of Promise.all() will immediately enter the rejected state, so that when entering the rejected state through Promise.all(), the source Promise may still be in the pending state, so that all Promises cannot be obtained The timing of completion.

The Promise.allSettled() static method will wait for all source Promises to enter the fulfilled or rejected state, so as to ensure that there will be no timing conflicts.

race method

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

const p = Promise.race([p1, p2, p3]);
  1. As long as one instance among p1, p2, and p3 changes state first, the state of p will change accordingly
  2. The return value of the first changed Promise instance is passed to the callback function of p

Syntactic sugar Async/Await

PromiseAdded syntactic sugar in ES8 async awaitto handle asynchrony more gracefully.

asyncIt can exist alone, and the function declared with this keyword returns a Promise object.

async funtion add(){
    
    
    return 1
}
add()
add() instanceof Promise // true

awaitIt cannot exist alone, it must be used asynctogether

function sub() {
    
    
    await 1
}
// 这个方法定义就不满足语法的,会如下报错
// Uncaught SyntaxError: await is only valid in async function

async awaitMake asynchronous processing more elegant

let fs = require('fs')

var  gen = async function() {
    
    

    const f1= await readFile('files/a.txt');//封装一个promise对象
    console.log(f1)
    const f2=  await readFile('files/b.txt');
    console.log(f2)
    const f3=  await readFile('files/c.txt');
    console.log(f3)
  
  };


  var readFile=function(path){
    
    
     return  new Promise((resolve,reject)=>{
    
    
        fs.readFile(path,'utf-8',function(err,data){
    
    
            if(!err){
    
    
          
             resolve(data)
            }else{
    
    
              reject(err)
            }
            
         });
      })
   
}


  
var obj = gen();

Guess you like

Origin blog.csdn.net/weixin_43183219/article/details/124318663