关于async_await的同步和异步执行(多个异步函数实现同步执行方法)

在正常的同步执行下,一般都用 await 进行等待异步执行完成之后再进行操作,那么多个异步请求的时候该怎么办呢(多个异步函数实现同步执行方法)?
如下所示:

mounted() {
    
    
  this.getPerson()
},
methods: {
    
    
  getName() {
    
    
    return new Promise((resolve, reject) => {
    
    
      setTimeout(() => {
    
    
        resolve('xiaoming')
      }, 2000)
    })
  },
  getAge() {
    
    
    return new Promise((resolve, reject) => {
    
    
      setTimeout(() => {
    
    
        resolve('18')
      },3000)
    })
  },
  async getPerson() {
    
    
    console.log('开始时间:', new Date());
    const name = await this.getName()
    const age = await this.getAge()
    console.log('结果:', name + '-' + age);
    console.log('结束时间:', new Date());
  }
}

当 getName 和 getAge 都是异步操作的时候,运行结果会如下所示:
image.png
可以发现结果是在 5 秒后返回结果的,但是上面两个都是异步操作,明显可以缩短时间简化成 3 秒返回结果,那么要如何优化呢?
其实在 Promise 构造函数执行时会立即调用 executor 函数,把 resolve 和 reject 两个函数作为参数传递给 executor ,executor 函数在 Promise 构造函数返回新建对象前被调用。resolve 和 reject 函数被调用时,分别将 promise 的状态改为 fulfilled(完成)或 rejected(失败)。executor 内部通常会执行一些异步操作,一旦完成,可以调用 resolve 函数来将 promise 状态改成 fulfilled,或者在发生错误时将它的状态改为 rejected。
所以可以优化成如下所示代码(方法一):

async getPerson() {
    
    
  console.log('开始时间:', new Date());
  const namePromise = this.getName()
  const agePromise = this.getAge()
  const name = await namePromise
  const age = await agePromise
  console.log('结果:', name + '-' + age);
  console.log('结束时间:', new Date());
}

可以看到执行时间变为了 3 秒,这是因为通过变量获取异步函数的时候 Promise 构造函数这时候已经执行了。
image.png
当然也可以使用 Promise.all 的方法(方法二):

async getPerson() {
    
    
  console.log('开始时间:', new Date());
  const [name, age] = await Promise.all([this.getName(), this.getAge()])
  console.log('结果:', name + '-' + age);
  console.log('结束时间:', new Date());
}

可以看到返回的结果也是过了 3 秒:
image.png

猜你喜欢

转载自blog.csdn.net/qq_43651168/article/details/131430929