js 的 异步处理

264 阅读2分钟

在 es5 年代,只有callback,我们的异步非常好理解,就是不管cb,同步代码继续执行呗 但当有了async await 以后,我们执行

async created () {
      this.getTopicbaseInfo();
}
async getTopicbaseInfo () {
      console.log('getTopicbaseInfo1 await');
      const res: Ajax.AxiosResponse = await api.topicApi.getTopicbaseInfo();
      console.log('getTopicbaseInfo1 await after');
      console.log('getTopicbaseInfo2 await');
      const res2: Ajax.AxiosResponse = await api.topicApi.getTopicbaseInfo();
      console.log('getTopicbaseInfo2 await after');
}

浏览器输出 这些console.log都是按顺序输出的,这不就全部成同步了吗?那么异步是不是失去了他本来的作用呢?

async await 的出现就是让异步代码像同步一样执行,那我们的异步去哪里了呢?让我们在原来的代码里面增加一个函数

async created () {
	  this.getTopicbaseInfo();
      this.getTopicInfo();
}
async getTopicbaseInfo () {
      console.log('getTopicbaseInfo1 await');
      const res: Ajax.AxiosResponse = await api.topicApi.getTopicbaseInfo();
      console.log('getTopicbaseInfo1 await after');
      console.log('getTopicbaseInfo2 await');
      const res2: Ajax.AxiosResponse = await api.topicApi.getTopicbaseInfo();
      console.log('getTopicbaseInfo2 await after');
}
async getTopicInfo () {
      console.log('getTopicInfo await');
      const res: Ajax.AxiosResponse = await api.topicApi.getTopicInfo();
      console.log('getTopicInfo await after');
}

我们看到,

'getTopicbaseInfo1 await'
'getTopicInfo await'

这个输出表明,create函数中,调用this.getTopicbaseInfo();this.getTopicInfo();不会管返回值,而是直接同步执行。 而在往后的输出

'getTopicInfo await after',
'getTopicbaseInfo1 await after',

异步执行,也就是说在各自的await之后执行。

最后执行的是

'getTopicbaseInfo2 await'
'getTopicbaseInfo2 await after'

跟在了:

getTopicbaseInfo1 await afte

之后,异步执行。

最后总结一下,在async await中的代码,被异步执行,但跟在await后面的代码像同步代码一样执行。而调用async的函数不管异步返回值直接同步执行,这就完全能够保存异步函数的特性,同时发挥了async await像同步代码一样执行异步代码的作用。

课后小测验

async created () {
	  this.getTopicbaseInfo();
      this.getTopicInfo();
}
async getTopicbaseInfo () {
      console.log('getTopicbaseInfo1 await');
      const res: Ajax.AxiosResponse = await api.topicApi.getTopicbaseInfo();
      console.log('getTopicbaseInfo1 await after');
      console.log('getTopicbaseInfo2 await');
      const res2: Ajax.AxiosResponse = await api.topicApi.getTopicbaseInfo();
      console.log('getTopicbaseInfo2 await after');
}
async getTopicInfo () {
            const res: Ajax.AxiosResponse = await api.topicApi.getTopicInfo();
            console.log('getTopicInfo3 await after');
            this.topicInfo = res.data;
            console.log('getTopicInfo4 await');
            const res2: Ajax.AxiosResponse = await api.topicApi.getTopicInfo();
            console.log('getTopicInfo4 await after');

输出

1、3同步执行,1after异步执行,2紧接着同步执行,3after异步执行, 4同步执行,2,4异步执行后返回。 其中 await after 的顺序可能有出入,只有同步执行的代码是顺序保证的