今天有幸好碰到一个bug,让我知道了之前我对await async 的理解有点偏差。

错误的理解

之前我一直以为  await 后面的表达式,如果是直接返回一个具体的值就不会等待,而是继续执行async function 中的函数, 如下demo:

 method () {
getParams () {
let params = {}
if (this.serachFrom.time !== 0) {
params.month = this.serachFrom.time.substr(5, 2)
params.year = this.serachFrom.time.substring(0, 4)
}
return params
},
async testNoAwait () {
console.log('run testNoAwait')
return 'this is no await'
},
async testAsync () {
console.log('run testAsync')
let params = this.getParams()
const data = await this.$store.dispatch('initSchemeTimeTest', params)
return data
},
async test () {
console.log('test start')
const v1 = await this.testNoAwait()
console.log(v1)
const v2 = await this.testAsync()
console.log(v2)
console.log(v1, v2)
}
},
created () {
console.log('this is run created ')
this.test()
console.log('test last ...')
console.log('test end ...')
}

如上程序我之前认为   await this.testNoAwait() 会直接执行完不会等待,继续执行   console.log(v1),如果这样那么是一个错误的理解。

实际上MDN描述的暂停执行,并不是真正的暂停,而是让出了线程(跳出async函数体)然后继续执行后面的语句。

完整 demo code

vue  created

async created () {
console.log('this is run created ')
this.test()
// let data = this.test()
// console.log(data)
console.log('test last ...')
console.log('test end ...')
this.testSayHello()
}

vue  methods

testSayHello () {
console.log('this is run hello')
},
getParams () {
let params = {}
if (this.serachFrom.time !== 0) {
params.month = this.serachFrom.time.substr(5, 2)
params.year = this.serachFrom.time.substring(0, 4)
}
return params
},
testNoAwait () {
console.log('run testNoAwait')
return 'this is no await'
},
async testAsync () {
console.log('run testAsync')
let params = this.getParams()
const data = await this.$store.dispatch('initSchemeTimeTest', params)
return data
},
async test () {
console.log('test start')
const v1 = await this.testNoAwait()
console.log(v1)
const v2 = await this.testAsync()
console.log(v2)
console.log(v1, v2)
}

vuex 中

// actions
async initSchemeTimeTest ({commit, state, dispatch}, params) {
console.log('run initSchemeTimeTest')
const data = await schemeListTest(params)
console.log('开始返回结果')
commit(types.SCHEME_DATA_TIME_LIST, data)
return data
}

services api 中

注意在 testAsync 中  dispatch 了 initSchemeTimeTest,然后在调用了服务端的 schemeListTest

export async function schemeListTest (params) {
console.log('this is run server')
const data = await postTest(`/provid/spot/dailydeclareschemestatus/list`, params)
return data
}

common 中封装的 axiosServer

export function postTest (url, params) {
return new Promise(async (resolve, reject) => {
try {
console.log('this is run common')
const {
data:
{
respHeader,
respBody
}
} = await axiosServer({
url,
type: 'post',
params: {
reqBody: params
}
})
if (respHeader.needLogin && process.env.NODE_ENV !== 'development') {
Message.error(respHeader.message)
location.href = condition.frontDomain + `/login?redirect=${encodeURI(condition.frontDomain + '/spot/race')}`
reject(respHeader.message)
}
if (respHeader.resultCode === 0) {
resolve(respBody || respHeader.message)
} else {
if (respHeader.resultCode === 21050 && respBody) {
Message.error(respHeader.message)
resolve(respBody)
} else if (respHeader.message === '您没有该应用的权限') {
location.href = 'frame.huidiancloud.com'
} else {
Message.error(respHeader.message)
reject(respHeader.message)
}
}
} catch (e) {
reject(e)
Message.error('系统繁忙,请稍后再试!')
}
})
}

如果按照之前的理解那么这个应该是输出了 run testNoAwait  之后继续输出  this is no await 。

控制台运行结果:

执行顺序

js是单线程(同时只能干一件事情),

以上测试的关键点在于当程序碰到await 时,把后面的表达式执行一次,然后把resolve 函数或者reject 函数(await 操作符会把表达式的结果解析成promise 对象) push 回调队列,接着跳过当前这个async function ,执行async function 后面的代码,如上面代码中,执行 this.testNoAwait() 之后就跳过 this.test()这个方法,执行了

console.log('test last ...')
console.log('test end ...')
this.testSayHello()

至于什么时候知道这个promise 对象的状态,这就是事件循环的事情了,监听到这个异步的状态事件改变时,如果执行环境栈是空的那么就会执行取出回调队列中的回调,推入执行环境栈,然后继续async function 后面的语句。

vue 开始执行created 生命周期

输出:this is run created

输出:test start

执行:testNoAwait  // 关键

输出 :run testNoAwait 之后 跳过 test() 函数 执行created 后面的语句

输出:test last ... 、test end ... 、this is run hello

程序回到

const v1 = await this.testNoAwait()

如果监听到这个异步事件完成 则开始执行 后面的代码所以会

输出:this is no await

下面这个 await 跟上面同理

const v2 = await this.testAsync()

await 后面的表达式执行一次,如果里面存在await 也是同理继续执行下去,执行完之后,跳过这个async function 等到异步操作完成了继续回到 const v2 这里执行。

这里需要注意的是在common 中的postTest 中构造的Promise 对象是立即执行传入的function 所以在 services api 输出了 this is run server  之后接着输出 this is run common

因为上面的列子不是很方便看,所以我写了一个简单的测试 :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
<meta content="yes" name="apple-mobile-web-app-capable">
<meta content="black" name="apple-mobile-web-app-status-bar-style">
<meta content="telephone=no,email=no" name="format-detection">
<meta name="App-Config" content="fullscreen=yes,useHistoryState=yes,transition=yes">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>async await demo</title>
</head>
<body>
<h1>async await demo</h1>
</body>
<script> async function async1() {
console.log('async1 start')
await async2()
console.log('async1 end')
}
async function async2() {
console.log('async2')
await async3()
}
async function async3() {
console.log('async3')
await async4()
console.log('async4 end')
}
async function async4() {
return new Promise(function (resolve, reject) {
console.log('async4')
resolve()
})
}
console.log('script start')
setTimeout(function () {
console.log('setTimeout')
}, 0)
async1();
new Promise(function (resolve) {
console.log('promise1')
resolve();
}).then(function () {
console.log('promise2')
})
console.log('script end') // script start async1 start async2 async3 async4 promise1 script end promise2 async4 end async1 end setTimeout </script>
</html>

async awiat 执行顺序关键点

  1. 事件循环机制
  2. 回调队列
  3. 执行环境栈、入栈、出栈
  4. Promise 的构造函数是立即执行,但是他的成功、失败的回调函数是一个异步执行的回调
  5. Promise 的回调优先于 setTimeout 的任务队列
  6. async 返回promise 对象
  7. await 表达式的作用和返回值

总结

1、js 是单线程(同时只能做一件事情),在js引擎内部异步的处理是跟事件循环机制、以及回调队列有关

2、构造的promise 对象是立即执行传入的function

3、async function 是返回一个promise 对象

4、await 操作符会把表达式的结果进行解析成promise 对象

错误的理解引起的bug async await 执行顺序的更多相关文章

  1. async/await 执行顺序详解

    随着async/await正式纳入ES7标准,越来越多的人开始研究据说是异步编程终级解决方案的 async/await.但是很多人对这个方法中内部怎么执行的还不是很了解,本文是我看了一遍技术博客理解 ...

  2. setTimeout,promise,promise.then, async,await执行顺序问题

    今天下午看了好多关于这些执行顺序的问题  经过自己的实践 终于理解了  记录一下就拿网上出现频繁的代码来说: async function async1() { console.log('async1 ...

  3. Promise嵌套问题/async await执行顺序

    /* 原则: 执行完当前promise, 会把紧挨着的then放入microtask队尾, 链后面的第二个then暂不处理分析, */ 一. new Promise((resolve, reject) ...

  4. 事件循环 EventLoop(Promise,setTimeOut,async/await执行顺序)

    什么是事件循环?想要了解什么是事件循环就要从js的工作原理开始说起: JS主要的特点就是单线程,所谓单线程就是进程中只有一个线程在运行. 为什么JS是单线程的而不是多线程的呢? JS的主要用途就是与用 ...

  5. 理解ES7中的async/await

    理解ES7中的async/await 优势是:就是解决多层异步回调的嵌套 从字面上理解 async/await, async是 "异步"的含义,await可以认为是 async w ...

  6. 创建HttpFilter与理解多个Filter代码的执行顺序

    1.自定义的HttpFilter,实现Filter接口 HttpFilter package com.aff.filter; import java.io.IOException; import ja ...

  7. 理解Task和和async await

    本文将详解C#类当中的Task,以及异步函数async await和Task的关系 一.Task的前世今生 1.Thread 一开始我们需要创建线程的时候一般是通过Thread创建线程,一般常用创建线 ...

  8. 理解C#中的 async await

    前言 一个老掉牙的话题,园子里的相关优秀文章已经有很多了,我写这篇文章完全是想以自己的思维方式来谈一谈自己的理解.(PS:文中涉及到了大量反编译源码,需要静下心来细细品味) 从简单开始 为了更容易理解 ...

  9. async和await执行顺序

    关于执行顺序和线程ID,写了一个小程序来检测学习: using System; using System.Net; using System.Threading; using System.Threa ...

随机推荐

  1. 【iMooc】全面解析java注解

    在慕课上学习了一个关于java注解的课程,下面是笔记以及一些源码. Annotation——注解 1.JDK中的注解 JDK中包括下面三种注解: @Override:标记注解(marker annot ...

  2. PerfMon Metrics Collector插件的Disks I/O使用总结

    做Jmeter测试的时候如果想要统计磁盘的IO读写速度,那么很容易想到用PerfMon Metrics Collector这个插件,但是具体使用过程中还有以下需要注意的. 1.如下图首先,需要选择监控 ...

  3. CentOS 简单学习 firewalld的使用

    1. centos7 开始 使用firewalld 代替了 iptables 命令工具为 firewall-cmd 帮助信息非常长,简单放到文末 2. 简单使用 首先开启 httpd 一般都自带安装了 ...

  4. K8S 使用简单的NFS 作为 持久存储的 StorageClass 的简单测试.

    Study From https://jimmysong.io/kubernetes-handbook/practice/using-nfs-for-persistent-storage.html 1 ...

  5. SSM 全局异常

    转载: http://blog.csdn.net/m13321169565/article/details/7641978 废话不多,直接说重点. 一  创建异常拦截类 (这里将  webapi 和 ...

  6. BZOJ 2663: [Beijing wc2012]灵魂宝石

    2663: [Beijing wc2012]灵魂宝石 Time Limit: 5 Sec  Memory Limit: 128 MBSubmit: 261  Solved: 108[Submit][S ...

  7. 洛谷 P1361 小M的作物 解题报告

    P1361 小M的作物 题目描述 小M在MC里开辟了两块巨大的耕地\(A\)和\(B\)(你可以认为容量是无穷),现在,小\(P\)有\(n\)中作物的种子,每种作物的种子有1个(就是可以种一棵作物) ...

  8. jquery生成二维码并实现图片下载

    1.引入jquery的两个js文件 <script src="../scripts/erweima/jquery-1.10.2.min.js"></script& ...

  9. java基础知识代码-------枚举类型

    package com.mon10.day22; /** * 类说明 :枚举类型,案例二 * * @author 作者 : chenyanlong * @version 创建时间:2017年10月22 ...

  10. python 基础数据类型之str

    1.字符串去除空格 # S.strip(self, chars=None) #去除字符串两端空格# S.lstrip(self, chars=None) #去除字符串左端空格# S.rstrip(se ...