Let’s start with a piece of code

Mock request:

let getData = function (time) {
  return new Promise((resolve) = >{
    setTimeout((a)= >{
      resolve(1); },time); })}Copy the code

Use await, async functions:

async function asyncFun() {
  const a = await getData(1000);
  console.log(a);
  const b = await getData(2000);
  console.log(b);
  return a+b;
}

async function test(){
    console.log(await asyncFun());
}

Copy the code

When we execute test we print 1, 2 in order on the console

With this in mind, I wrote the following code:

function* asyncFun() {
  const a = yield getData(1000);
  console.log(a);
  const b = yield getData(2000);
  console.log(b);
  return a+b;
}

function* test() {
  console.log(await asyncFun());
}
Copy the code

Now the goal is to expect the same effect from test, but we know that generate is not automatic, so we need to wrap the high-order function:

const asyncFun2 = asyncFN(asyncFun);
const test2 = asyncFN(test);
Copy the code

We just need to let asyncFN do it for us. Now let’s see how it works:

const asyncFN = (work) = >{
  let gen = work();
  const wait = (a)= >{
    return new Promise((resolve) = >{
      const run = (res) = >{
        res = gen.next(res);
        if(res.done){
          resolve(res.value)
        }else {
          res.value.then((v) = >{ run(v) }) } }; run(); })};return wait;
};
Copy the code

So that’s my thought process. Just a quick note