Promise, Async/Await Detailed Explanation

1. What is Promise

        Promise is a component that abstracts asynchronous processing objects and performs various operations on them. Promise itself is a synchronous immediate execution function to solve the problem of asynchronous callback. When the resolve or reject callback function is called for processing, it is an asynchronous operation. Then/catch will be executed first, and resolve will be called and executed after the main stack is completed. The method stored in /reject.

        The function of promise is to easily model complex asynchronous processing. Using Promise to read multiple files continuously can solve the callback hell.

When it comes to JavaScript-based asynchronous processing, I think most of them will think of using callback functions.

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

       Promise standardizes similar asynchronous processing objects and processing rules, and writes them according to a unified interface, and writing methods other than the specified methods will cause errors.

// 使用Promise进行异步处理的一个例子
var promise = getAsyncPromise("fileA.txt"); 
promise.then(function(result){
    // then 获取文件内容成功时的处理
}).catch(function(error){
    // catch 获取文件内容失败时的处理
});

        Promise itself is a synchronous immediate execution function . When resolve or reject is executed in the executor, it is an asynchronous operation at this time, and then/catch will be executed first. After the main stack is completed, the method stored in resolve/reject will be called implement.

console.log('script start')
let promise1 = new Promise(function (resolve) {
    console.log('promise1')
    resolve()
    console.log('promise1 end')
}).then(function () {
    console.log('promise2')
})
setTimeout(function(){
    console.log('settimeout')
})
console.log('script end')
// 输出顺序: script start->promise1->promise1 end->script end->promise2->settimeout

2. API method of ES6 Promises

 1. Parameters: The Promise constructor accepts a function as a parameter, and the parameter accepts two functions as its own parameters, namely resolve and reject.

new Promise((resolve, reject) => {
    //异步操作
})

promise.then(function(data) {
    console.log('success');
}).catch(function(error) {
    console.log('error');
});

1.1  resolve

        Return the successful state of a promise object, and notify the then method or catch method, then decide which way to go according to the state of the object, and then perform subsequent operations; the role of the resolve method is to change the state of the promise object from in progress to completed Completed, at the same time, parameters can be passed to the resolve method, which will be obtained by the then method of the promise object in the future;

1.2  reject

       Return a failed promise object; the reject method is the same, it just changes the state of the promise object to failure, and the parameters passed in will be obtained by the catch method;

        After resolve or reject modifies the state of the promise object, it is determined whether to execute the then or catch callback method by detecting the state of the promise object. In this process: resolve and reject play the role of modifying the object state, notifying the callback function, and passing the parameters that the callback function may need. The advantage of this is that the logical judgment and the callback function are processed separately;

2. Callback functions .then and .catch 

The call of the callback function is completed according to the status of the object: in progress, completed and failed (pending (in progress) , fullyfilled (success) , rejected (failure)

2.1  Promise.then

1. Get the correct result of the asynchronous task;

2. Only when the internal state of Promsie is settled, the corresponding handler in the then method will be executed;

3. The power of the then method can be chained;

2.2  Promise.catch

Capture and process failure results;

3. Methods .all() and .race() 

3.1  Promise.all()

  1. Process multiple asynchronous tasks concurrently (waiting mechanism), and print them uniformly after all results are returned;
  2. Whoever runs slowly will execute the callback;
  3. Promise.all  receives an array of promise objects as a parameter, and it will call the method when all the promise objects in the array change to resolve or reject state  .then ;
let wake=(time)=>{
    return new Promise(function (resolve,reject){
        setTimeout(()=>{
            resolve(`${time/1000}秒后醒来`);
        },time);
    });
}
let p1=wake(10000);
let p2=wake(1000);
Promise.all([p1,p2]).then(res=>{
    let [res1,res2]=res;
    console.log(res1,res2);
}).catch(err=>{
    console.log(err);
})

// 执行结果:10秒后醒来 1秒后醒来

3.2  Promise.race()

  1. Process multiple asynchronous tasks concurrently (racing mechanism). When any asynchronous operation is completed, the next step is executed. then; used when requesting pictures;
  2. Whoever runs faster will execute the callback;
let p1=new Promise((resolve,reject)=>{
    setTimeout(()=>{
            resolve('success');
        }, 10000);
});

let p2=new Promise((resolve,reject)=>{
    setTimeout(()=>{
        reject('faild');
    }, 500);
});

Promise.race([p1,p2]).then(res=>{
    console.log(res);  
}).catch(err=>{
    console.log(err); // 返回的是faild
})

3. What is async/await

        async/await simplifies Promise asynchronous operations (syntactic sugar);

        The async function returns a Promise object. When the function is executed, once it encounters an await, it will return first. After the triggered asynchronous operation is completed, the following statement in the function body will be executed. It can be understood as giving up the thread and jumping out of the async function body.

async function async1(){
   console.log('async1 start');
    await async2();
    console.log('async1 end')
}
async function async2(){
    console.log('async2')
}

console.log('script start');
async1();
console.log('script end')

// 输出顺序:script start->async1 start->async2->script end->async1 end

1. async syntax

  1. Automatically convert regular functions into Promise, and the return value is also a Promise object;
  2. The callback function specified by the then method will be executed only after the asynchronous operation inside the async function is executed;
  3. await can be used inside asynchronous functions;

2. await syntax

1. await is placed before the Promise call, and await forces the following code to wait until the Promise object resolves, and the resolved value is obtained as the operation result of the await expression; 2. await can only be
used inside the async function, and it can be used in ordinary functions will report an error;

3. Error handling

       In the async function, whether it is the Promise rejected data or the logical error report, it will be silently swallowed, so it is best to put await in try{}catch{}, and the catch can capture the rejected data of the Promise object or the exception thrown

function timeout(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {reject('error')}, ms);  //reject模拟出错,返回error
  });
}
async function asyncPrint(ms) {
  try {
     console.log('start');
     await timeout(ms);  //这里返回了错误
     console.log('end');  //所以这句代码不会被执行了
  } catch(err) {
     console.log(err); //这里捕捉到错误error
  }
}

asyncPrint(1000);

// 执行结果: start
             error

Guess you like

Origin blog.csdn.net/m0_61663332/article/details/132086559
Recommended