103 lines
2.2 KiB
Markdown
103 lines
2.2 KiB
Markdown
# async swait
|
|
|
|
```js
|
|
/**
|
|
* sync 同步 async 异步
|
|
* 通过 async 快速创建异步函数
|
|
* 异步函数的返回值会自动封装到一个Promise中
|
|
* 提供了 await , 可以用同步的形式写异步代码
|
|
* 会暂停代码的执行, 直到异步代码有结果才将结果返回
|
|
*
|
|
* 重点: 1. await 只能用于async声明的异步函数中, 或者es模块的顶级作用域
|
|
* 2. 需要通过 try{}catch(){} 处理异常
|
|
* 3. async声明的函数里没有使用await, 就相当于{}里的内容放到new Promise(()=>{})的括号里, 立刻执行
|
|
*
|
|
* es模块的顶级作用域:
|
|
* 1. html页面中 <script type="module">await console.log(111)</script>
|
|
* 2. nodejs创建 xx.mjs 中 await console.log(111)
|
|
*/
|
|
```
|
|
|
|
```js
|
|
const result = async () => {
|
|
return 10
|
|
}
|
|
|
|
console.log('result', result)
|
|
|
|
result().then(res => {
|
|
console.log('res', res)
|
|
})
|
|
```
|
|
|
|
```js
|
|
// await 只能用于async声明的异步函数中
|
|
const sum = (a, b) => {
|
|
return new Promise(resolve => {
|
|
setTimeout(() => {
|
|
resolve(a + b)
|
|
}, 1000)
|
|
})
|
|
}
|
|
|
|
const count = async () => {
|
|
let a = await sum(1, 2)
|
|
let b = await sum(a, 3)
|
|
let c = await sum(b, 4)
|
|
console.log('c', c)
|
|
}
|
|
|
|
count()
|
|
```
|
|
|
|
```js
|
|
// async声明的函数里没有使用await, 就相当于{}里的内容放到new Promise(()=>{})的括号里, 立刻执行
|
|
const f1 = async () => {
|
|
console.log(1)
|
|
console.log(2)
|
|
console.log(3)
|
|
}
|
|
f1()
|
|
console.log(4)
|
|
|
|
// 等价于
|
|
const f1_ = () => {
|
|
return new Promise(resolve => {
|
|
console.log(1)
|
|
console.log(2)
|
|
console.log(3)
|
|
resolve()
|
|
})
|
|
}
|
|
```
|
|
|
|
```js
|
|
// await 也可以放到同步代码前面
|
|
// await 调用函数后, await后面的所有代码会在 **当前代码执行完毕后** 被放到微任务队列
|
|
const f2 = async () => {
|
|
console.log(1)
|
|
await console.log(2) // console.log(2)正常执行
|
|
console.log(3) // 后面的被放到微任务队列
|
|
}
|
|
f2()
|
|
console.log(4)
|
|
// 1, 2, 4, 3
|
|
|
|
// 等价于
|
|
const f2_ = () => {
|
|
return new Promise(resolve => {
|
|
console.log(1)
|
|
console.log(2)
|
|
}).then(() => {
|
|
console.log(3)
|
|
})
|
|
}
|
|
|
|
```
|
|
|
|
```js
|
|
;(async()=>{
|
|
console.log('记得加分号') // js自动加分号可能出错
|
|
})()
|
|
```
|