例如:进入某个页面,需要先登录调用login()函数,拿到用户信息之后,再调取用户商品信息getInfo()函数,用Promise实现:
var promise = new Promise((resolve, reject) => {
this.login(resolve)
})
.then(() => this.getInfo())
.catch(() => { console.log("Error") })
async函数,使得异步操作变得更加方便,下面我们用async来实现:
async function asyncFunc(params) {
const result1 = await this.login()
const result2 = await this.getInfo()
}
顺序处理多个异步结果:
async function asyncFunc() {
const result1 = await otherAsyncFunc1();
console.log(result1);
const result2 = await otherAsyncFunc2();
console.log(result2);
}
并行处理多个异步结果:
async function asyncFunc() {
const [result1, result2] = await Promise.all([
otherAsyncFunc1(),
otherAsyncFunc2()
]);
console.log(result1, result2);
}