Detailed explanation of the evolution of handling asynchronous operations: callback function, Promise, Generator, async and await

Handling the evolution of asynchronous operations

Callback function ==> Promise object ==> Genarator function ==> async and await

Callback

The client-side JS runs in a single thread in the browser. It will execute the synchronous task first and then execute the asynchronous task to ensure that the running process is not blocked, but sometimes we need to get the result of the previous asynchronous task before calling a synchronous task, so we need The callback function helps to achieve this.

 <script>
        function getMessage(msg,callback){
    
    
            setTimeout(() => {
    
    
                console.log(msg);
                callback();
            }, 2000);
        }
        function waitMe(){
    
    
            console.log("wait me!");
        }
        getMessage("helloYokia",waitMe)

    </script>
Disadvantages of callback function:
  • The essence is nested functions, but the code is seriously coupled, which is not conducive to viewing and modifying.
  • Correcting errors is very difficult, and you cannot capture and return the wrong results.

Promise object

advantage:
  • Solved the problem of nested callback hell.
Disadvantage

But the chain operation of .then.then is also very complicated, and a new Promise must be created to handle the corresponding (equivalent to a nanny at home) and assign the data to a new variable. Let me
give you a little chestnut used in promises:
No babysitter, I personally realized a series of ideas in my mind one by one:
I want to knit a scarf and give it away!

 function 买材料(resolve,reject) {
    
    
            setTimeout(function () {
    
    
                resolve(['毛线', '毛线针']);
            }, 3000)
        }
        function 织围巾(resolve, reject) {
    
    
            setTimeout(function () {
    
    
                //用买到的材料开始织围巾
                resolve({
    
    
                    成品: '围巾',
                    附加品: '一封信',
                    打包: "礼物盒包装一下"
                })
            }, 3000)
        }
        function 送礼物(resolve,reject) {
    
    
            //对送礼物的结果进行下一步处理
            resolve('某人感动的稀里哗啦');
        }
        function 回礼() {
    
    
            //回礼后的下一步处理
            resolve('我得到了一枚鹅蛋大的钻戒吼吼吼~')
        }

The idea is over, put it into action!

new Promise(买材料)
//用材料织围巾
.then((材料)=>{
    
    
    return new Promise(织围巾);
})
.then((围巾)=>{
    
    
    return new Promise(送出礼物);
})
.then((感动&痛哭)=>{
    
    
    回礼();
}).catch(err => {
    
    
    console.log(err);
});

In addition, any errors in the middle step can be captured and output in the final .catch.

Three states
  • pending: executing
  • resolve: successful callback function
  • reject: the failed callback function
    (the state of the promise can only be changed once.)
Promise commonly used api
  • Promise.reject

Class method, and the only difference from resolve is that the status of the returned promise object is rejected.

  • Promise.prototype.then

Instance method, register the callback function fn(vlaue){} for the Promise. The value is the return result of the previous task. The function in then must return a result or a new Promise object before the subsequent then callback can receive it.
Note: If the follow-up task is an asynchronous task, you need to use the new Promise object to return, and use return synchronously.

  • Promise.prototype.catch

Instance method, catch exception, function form: fn(err){}, err is the exception information thrown by the callback before catch registration.

  • Promise.race

Class method, multiple Promise tasks are executed at the same time, and return the result of the Promise task whose execution ends first, regardless of whether the Promise result succeeds or fails.

  • Promise.all

Class method, multiple Promise tasks are executed simultaneously.
If all are executed successfully, the execution results of all Promise tasks are returned in an array. If a Promise task is rejected, only the result of the rejected task is returned.

Generator

Simple generator function

function* g() {
    
    
    yield 'a';
    yield 'b';
    yield 'c';
    return 'ending';
}

var gen = g();
gen.next(); // 返回Object {
    
    value: "a", done: false}
gen.next(); // 返回Object {
    
    value: "a", done: false}
gen.next(); // 返回Object {
    
    value: "a", done: false}
gen.next(); // 返回Object {
    
    value: "ending", done: true}
//return后再写一行 没有意义
gen.next(); //{
    
    value: undefined, done: true}

generator translation: producer; yield translation: output

The characteristics of the Generator function are:

1. It can be executed in
stages, and it can be paused. 2. It can control the stage and the return value of each stage.
3. It can know whether the execution reaches the end.

async await

async testAsync() {
    
    
  try {
    
    
     await getJSON()
  } catch(err) {
    
    
     console.log(err)
  }
  ...剩下的代码
}

Guess you like

Origin blog.csdn.net/weixin_47067248/article/details/109946687