For those unfamiliar with Generator, take a look at Generator’s documentation: developer.mozilla.org/zh-CN/docs/…

preface

Prior to ES2017, we relied on generators to write asynchronous logic as synchronous code, for example:

function getJSONFile() {
  return new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve({
        name: Legend of the Desert.age: 23,}}),1000)})}function getHobby() {
  return new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve({
        hobby: ['climbing the mountain'.'travel'.'music'.'Go to the movies'.'Reading a novel'.'Play games']})},1000)})}function* gen(i) {
  let me = yield getJSONFile();
  console.log('me:', me);
  let hobby = yield getHobby();
  console.log('hobby:', hobby)
}

function co(genFn) {
  let gen = genFn();
  let res = gen.next()
  let run = (gen, res) = > {
    if(! res.done){if(res.value&&(res.value.__proto__.constructor === Promise)){
        res.value.then((data) = > {
          letres2 = gen.next(data) run(gen, res2); })}else{
        let res3 = gen.next(res.value);
        run(gen, res3);
      }
    }
    
  }
  run(gen, res);
}

co(gen)
Copy the code

However, with ES2017 providing async && await, we can write this block of code in a more elegant way. Such as:

// async await
async function likeGen() {
  let me = await getJSONFile();
  console.log('me:', me);
  let hobby = await getHobby();
  console.log('hobby:', hobby);
  return 'end';
}

likeGen().then(res= > {
  console.log('res:', res);
})
Copy the code

Compared with async+await, the most obvious change is that there is less co function and less code. The rest of the code looks similar to the implementation using a Generator. So why is ES2017 providing async && await less code and more convenient for writing synchronous code?

The specific reasons will be introduced below. Let’s first look at the brief introduction of async && await.

Description of async && await function

async

The async Function declaration is used to define an asynchronous function that returns an AsyncFunction object. An asynchronous function is a function that executes asynchronously through an event loop and returns its result with an implicit Promise. But if your code uses an asynchronous function, its syntax and structure will look more like a standard synchronous function.

When an async function is called, a Promise object is returned. When the async function returns a value, the Promise’s resolve method takes care of passing the value; When async throws an exception, Promise’s Reject method also passes the exception.

Async functions may have await expressions, which cause the async function to pause, wait for the Promise result, and then resume the async function and return resolved.

Note that the await keyword is valid only in async function. If you use await outside async function, you will only get a SyntaxError.

await

The await operator is used to wait for a Promise object. It can only be used in async function.

Await expression suspends execution of the current async function until the Promise processing completes. If the Promise is fulfilled normally, the resolve function parameter of its callback will be the value of the await expression and the async function will continue to be executed.

If a Promise handles an exception (Rejected), the await expression throws the Promise’s exception reason.

Also, if the value of the expression after the await operator is not a Promise, the value itself is returned.

async+await VS generator

The purpose of introducing async and await in ES2017 is to simplify the complexity of writing synchronous code with generator, reduce the complexity of writing synchronous code with JS, reduce the amount of code and make the syntax simpler.

You can think of async and await as the simple upper syntactic sugar for synchronizing code with generator in the first half of the preface. This means that the browser implements the underlying part of the JS interpreter for us, and when we use async and await, the JS interpreter will read as generator+co functions (generator automatic execution functions implemented in the introduction).

In this way, we do not have to worry about generator and how to make generator execute automatically. To write synchronous code, we need to define an async function and await the asynchronous code with await. It is simple and convenient, and the amount of code is small.