1. What is Async?

What is async function? In short, it is the syntactic sugar of Generator functions.Copy the code

2. Improvements of Async over Generator functions

After reading through the ES6 documentation and how async is compiled in Babel, here's the summary: Generator functions are not self-executing and need to call the next() function. When encapsulating async, it essentially encapsulates a built-in auto-executor for Generator functions and processes the return result as a PromiseCopy the code

3. The implementation

Once we understand the nature of wrapping async functions, we can give the following code:Copy the code
/** * executes the Generator and returns a Promise object *@param {*} Fn Passes the generator function block *@returns * /
function asyncToGenerator(fn){
  return function(){
    const generatorFunc  =  fn.call(this.arguments);// In the generator function this points to the current scope
    / / return Promise
    return new Promise((resolve,reject) = >{
        function step(key,arg){
              let generatorResult;
              try{
                generatorResult =  generatorFunc[key](arg);// The argument passed to next() in the generator will be returned as the yield expression
              }catch(e){
                reject(e);//reject Generator error
              }
              // Next () returns an object of the form {value,done}. Value is the return value of the yield expression. Done indicates whether all yield expressions are completed
              const {done,value} = generatorResult;
              if(done){
                resolve(value)
              }else{
                return Promise.resolve(value).then(function onResolve(value){
                  step('next',value);
                },function onReject(reason){
                  step('throw',reason);
                })
              }
            }
        step('next');// The arG argument passed the first time was invalid}}})Copy the code