Difference between node asynchronous await and non-await

Posted by lucie on Tue, 10 Mar 2020 17:41:36 +0100

Items were recently written using nodes.The new node asynchronously uses the two keywords async/await.As we all know, these two keywords usually appear in pairs.However, the author finds that await does not need to wait for a return value.So what's the difference between wait plus and no?Baidu and google have a large amount of data, combined with comments, and finally understand in practice.The following is a direct example.

Without await

async test(ctx,next){
    this.doThing().then(console.log('done Thing'))
    this.doAnotherThing();
    console.log('to test');
  }

  async doThing() {
    this.doA();
    this.doB();
  }

  doAnotherThing() {
    console.log('do another thing')
  }

  async doA() {
    return new Promise(resove => {
      setTimeout(() => {
        console.log('done A')
        resove()
      }, 1000)
    })
  }

  async doB() {
    return new Promise(resove => {
      setTimeout(() => {
        console.log('done B')
        resove()
      }, 100)
    })
  }

After running the test function, the command line quickly prints the following results in turn

We see that no await, asynchronous function A,B is executed sequentially, because A runs for a long time, B executes first, and the whole process is not blocked.

Gaawait

async test(ctx,next){
    this.doThing().then(console.log('done Thing'))
    this.doAnotherThing();
    console.log('this way');
  }

  async doThing() {
    await this.doA()
    await this.doB()
  }

  doAnotherThing() {
    console.log('do another thing')
  }

  async doA() {
    return new Promise(resove => {
      setTimeout(() => {
        console.log('done A')
        resove()
      }, 1000)
    })
  }

  async doB() {
    return new Promise(resove => {
      setTimeout(() => {
        console.log('done B')
        resove()
      }, 100)
    })
  }

The results are as follows:

Since await was added, wait for asynchronous event A to complete before event B takes place.That is, await does not block the operation of synchronous events, but asynchronous is an execution, one of which is blocked and the next asynchronous event cannot continue.

summary

Obviously, await is not used every time.If no return value is required, executing without await will speed up the function.
(The above is a personal point of view. If it is wrong or insufficient, please criticize and correct it.)

Topics: Google