Asynchronous learning

Posted by tidou on Wed, 22 Sep 2021 02:53:11 +0200

(1)promise
1: Implementation principle
It is mainly realized through the callback function, which is encapsulated internally. The asynchronous code is expressed in the form of synchronization through the chain call of then method.
2:promise features
There are only three states: wait, success and failure
The state can only be changed once
3: promise's disadvantages
Once the execution cannot be cancelled, errors should be captured through the callback function
4: Difference between promise constructor call and promise chain call
The call to the constructor is executed immediately

new Promise((resolve, reject) => {
  console.log('new Promise')
  resolve('success')
})
console.log('finifsh')
// new Promise -> finifsh

Promise implements a chain call, that is, after calling then every time, a promise is returned, and it is a new promise. The reason is also that the state is immutable. If you use return in then, the value of return will be wrapped by Promise.resolve() `

Promise.resolve(1)
  .then(res => {
    console.log(res) // => 1
    return 2 // Package as Promise.resolve(2)
  })
  .then(res => {
    console.log(res) // => 2
  })

5: Implementation of promise

function myPromise(excus)
{
    let that=this;
    //Record current status
    that.state="pending";
    //Successful value
    that.value=null;
    //Reasons for failure
    that.rean=null;
    //Staging area is used to solve asynchronous tasks
    that.resolvedCallbacks = [];
    that.rejectedCallbacks = [];
  

    //Change the status of success
    function resovle(value)
    {
        if(that.state=='pending')
        {
            that.state="Resolve";
            that.value=value;
            that.resolvedCallbacks.forEach(item=>{
                item(value);
            })

        }
    }
    //Change failed state
    function reject(value)
    {
        if(that.state=='pending')
        {
            that.state='Reject';
            that.rean=value;
            that.rejectedCallbacks.forEach(item=>{
                item(rean);
            })
        }
    }
    
    //Execute now
    excus(resovle,reject);
}
//then
myPromise.prototype.then=function(resovle,reject){
    
    //Resolve asynchronous calls
    that=this;
    resovle =typeof resovle ==='function'?resovle:function(data){
        return data;
    }
    reject =typeof reject ==='function'?reject:function(err){
        throw err;
    }
    
   
    if(that.state=='pending')
    {
        that.resolvedCallbacks.push(resovle);
        that.rejectedCallbacks.push(reject);
    }
    return new myPromise((onfullfilled,Onreject)=>{
        if(that.state==='Resolve')
        {
            try{
            x=onfullfilled(that.value);
            console.log(x);
            resovle(x);
            }catch(e){
             reject(e);
            }
        }
    })

}

var p=new myPromise((resovle,reject)=>{
  setTimeout(() => {
    resovle('123');  
  }, 1000);
});
p.then((result) => {
   console.log(result);
},(err) => {
    console.log(err);
});

//promise implements asynchronous publisher subscription mode

6: Implementation of promisell

function promiseAll(Promises)
{
   return new Promise(function(resolve,reject){
     if(!Array.isArray(Promises))
     {
         return reject(new TypeError("argument"));
     }
     var countNum=0;
     var promiseNum=Promises.length;
     var resolvedvalue=new Array(promiseNum);
     for(let i=0;i<promiseNum;i++)
    {
        Promise.resolve(Promises[i]).then(function(value){
            countNum++;
            resolvedvalue[i]=value;
            if(countNum===promiseNum)
            {
                return resolve(resolvedvalue);
            }
        },function(reason){
            return reject(reason);
        })
    }
   })
}

var p1=Promise.resolve(1),
    p2=Promise.resolve(2),
    p3=Promise.resolve(3);
 
 promiseAll([p1,p2,p3]).then(function(value){
 	console.log(value)
 
 })

(2) : async and await
1: async function
It returns a promise object, encapsulated by promise.resolve()
2: await and async are used together
Advantages: compared with promise, it handles the chain call of then, which is more concise
Disadvantages: it will lead to performance degradation without dependency. It is more efficient to use promise.all() when there is no dependency.
Implementation principle of await:
It is mainly the combination of promise syntax sugar and generator. await is realized by generator to save the information in the current stack. When executing asynchronous code, read the information in the stack and combine it with the returned promise object

generator
When we instantiate a generator, we will return an Iterator.
Then, the execution order of the code is controlled through yield/next. When we execute yield, the execution of the code is suspended inside the generator function. The outside of the generator is still active, and the internal resources are retained, but in the suspended state.
When we execute next, we will start from the suspended position.

Why is next more than yield?
Because when we instantiate the generator, the code will not be executed immediately. We need to start the generator through next, and the subsequent yield corresponds to next. So next is one more than yield.

Topics: Javascript node.js Vue.js