更优雅的处理异步方式--async await

本文主要介绍 async await, ES7 新加的一种更为优雅的处理异步的方式。

async

表示函数中存在异步操作

1
2
3
4
// 语法
async function name(params) {
statements
}

await

await 只能在 async 函数中使用, 表示需要等待后面的表达式返回结果

1
2
// 语法
returnValue = await expression

注意 await 后面的 Promise 有可能返回的是 rejected, 所以最好把 await 放在 try···catch 中, 方便错误处理

1
2
3
4
5
try {
await expression
} catch (err) {
console.log(err)
}

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function test() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('status:resolve')
resolve('resolve')
}, 2000)
})
}

async function async() {
console.log('asyncfn start')
let result = await test()
console.log(result)
}

async()

function testFn(x) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(x)
}, 2000)
})
}

async function asyncFn(x) {
let a = await testFn(10)
let b = await testFn(20)
console.log(`${x}+${a}+${b}`)
}

asyncFn(30).then(() => {
console.log('asycnFn finished')
})