异步处理一直以来都是很麻烦的事情,而且很容易给系统带来意想不到的问题。
今天,给大家推荐一款非常新的语法功能:async-await,它属于es7语法,是基于promise和generator的语法糖。它的出现,让我们对代码中的异步处理更加便利、流畅,同时又极大增加了代码的可读性。
语法解释:
async:表示函数里有异步操作,返回promise对象
await:表示紧跟在后面的表达式需要等待结果。
注意:await 必须出现在 async 函数内部,不能单独使用。
基本用法:
async demo1(args) {
// ...do some code
const result = await demo2(args)
console.log(result)
// ...do some code
}
Await等待后面的表达式返回的promise对象状态变成resolved,如果等待的不是promise就会正常执行,不会进行等待
例:
结果:
Await返回的promise对象处理结果有可能是reject,怎么处理
1、使用catch方法
Await demo3(args).catch(err => {
// do some code for err
})
同时,在使用promise过程中也推荐使用catch方法来处理reject状态,当然,使用then的第二个参数定义回调函数也是可以的
2、使用try...catch
Try{
Await demo3(args)
}catch(err) {
// do some code for err
}
在什么场景下需要用到async-await
最常见的是,当多个请求间有依赖关系时,如两个请求,请求二的参数,来自于请求一的返回结果
Async demoFn() {
// do some code
Const apiResult1 = await api1(args)
Const apiResult2 = await api2(apiResult1)
// do some code
}
上述例子中,是多个请求间有依赖关系,如果是多个独立请求,它们之间没有任何联系又如何处理
1、还是使用上述方法
Await api1()
Await api2()
....
// do some code
2、由于多个api之间没有任何联系,所以可以多个异步方法同时处理
Const fn1 = api1()
Const fn2 = api2()
....
Const result = Await promise.all([fn1,fn2])
// do some code
|