回调函数的使用(第二个函数需要第一个函数出结果后再调用)

如题所述

第1个回答  2022-06-06
例如:进入某个页面,需要先登录调用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);

}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网