Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6+:async 原理 #18

Open
Chenjiayuan195 opened this issue May 26, 2020 · 1 comment
Open

ES6+:async 原理 #18

Chenjiayuan195 opened this issue May 26, 2020 · 1 comment

Comments

@Chenjiayuan195
Copy link
Owner

No description provided.

@Chenjiayuan195
Copy link
Owner Author

就是将Generator函数和自动执行器,包装在一个函数里

async function fn(args) {
    // ...
}
function fn(args) {
    return spawn(function* () {
        // ...
    })
}

spawn 函数就是自动执行器

function spawn(genF) {
  return new Promise(function(resolve, reject) {
    const gen = genF();
    function step(nextF) {
      let next;
      try {
        next = nextF();
      } catch(e) {
        return reject(e);
      }
      if(next.done) {
        return resolve(next.value);
      }
      Promise.resolve(next.value).then(function(v) {
        step(function() { return gen.next(v); });
      }, function(e) {
        step(function() { return gen.throw(e); });
      });
    }
    step(function() { return gen.next(undefined); });
  });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant