一.前言
在日常处理前端方法时,我们通常使用async和await或者是then方法,但是当方法多的时候,如何优雅的执行呢?
大家可以看看笔者对多个方法的解决思路。
二.解决方法
方法一:
直接aysnc,然后await
async getDataOne() {
res = await this.first()
res2 = await this.second()
res3 = await this.third()
}
方法二:
使用Promise的all方法
async getDataTwo() {
res = this.first()
res2 = this.second()
res3 = this.third()
await Promise.all([res, res2, res3])
}
方法三:
类似于then,执行对应firstResolve()和SecondResolve()就是证明对应方法执行完了
getDataThree() {
this.first()
new Promise(firstResolve => {
this.second()
firstResolve ()
}).then(_ => {
return new Promise(SecondResolve => {
this.third()
SecondResolve ()
})
)
}
三.总结
本文就是多个方法异步调用的一些方法的举例,本质上还是使用到了async、await和then方法。
大家有啥更加简洁的方法,欢迎评论区分享。