async
ECMAScript 8
特性
anync 函数
async
函数返回的是一个 Promise
对象
- 可以通过
.then
获取成功结果 - 可以通过
.catch
获取失败结果
javascript
const asFn = async () => {
return '1'
}
console.log(asFn()) // Promise{<fulfilled>: '1'}
// 调用
asFn().then(r => console.log(r)) // 1
.catch(e => console.log(e))
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
await 表达式
注意
如果 async
函数不用 await
那么,该函数与普通函数没区别,只是返回了一个 Promise
await
必须写在async
函数中await
右侧的表达式一般为promise
对象await
返回的是promise
成功的值await
的promise
失败了,就会抛出异常,需要通过try...catch
捕获处理