【问题标题】:Execution continues with await等待继续执行
【发布时间】:2021-02-10 18:25:36
【问题描述】:

我是异步等待的新手,我不确定它是否像我想的那样工作。搜索结果尚无定论,我需要有人为我指明正确的方向。

我有两个函数,addOrder(),它调用 getDistance() 函数来执行一些 api 工作,然后在我的数据函数(vue 应用程序)中设置“里程”。但是,似乎等待不起作用,就好像我在等待 getDistance 函数后立即尝试控制台记录“里程”一样,它仍然显示为空(它被初始化为什么)。任何见解都值得赞赏。

添加订单功能:

async addToOrder(){
   await this.getDistance()
   console.log(this.mileage) //problem is here, it shows the initialized value instead of the value changed in getDistance
}

获取距离函数

 async getDistance() {
      var origin = `${this.pickupPair.lat},${this.pickupPair.lng}`
      var dest = `${this.dropoffPair.lat},${this.dropoffPair.lng}`
      let miles
      //using google maps loader
      loader.load().then(() => {
        const service = new google.maps.DistanceMatrixService()
        service.getDistanceMatrix(
          {
            origins: [origin],
            destinations: [dest],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.IMPERIAL,
            avoidHighways: false,
            avoidTolls: false,
          },
          (response, status) => {
            if (status !== 'OK') {
              alert('Error was: ' + status)
            } else {
              const originList = response.originAddresses
              const destinationList = response.destinationAddresses

              this.mileage = response.rows[0].elements[0].distance.text
              this.mileage = this.mileage.replace(' mi', '')
              this.getCost()
            }
          }
        )
      })
    }

【问题讨论】:

  • 等待 this.getDistance().then(res=>console.log(res)) ?看起来你没有用 getDistance 返回任何东西?我知道的模式是你抓取数据,然后返回它——然后你在得到响应后操作对象,如果你在回调中操作东西——“this”关键字会变得很奇怪。

标签: javascript asynchronous async-await


【解决方案1】:

当您调用 loader.load().then() 时,您基本上要求它异步执行。 因此,该 getDistance 中的 javascript 将继续运行,并让该调用稍后发生。 这意味着 getDistance 将在 .then 内部发生任何事情之前返回。

有几个解决方案,但首先:

你知道 getDistanceMatrix 是否可以被称为 Promise 吗?

像这样: service.getDistanceMatrix(...).then()

还是只能通过传入回调函数得到结果?

这里有一些可能的解决方案,取决于 getDistanceMatrix 是否是 Promise。

// Full promise chaining
function getDistance() {
  return new Promise(resolve => {
    var origin = `${this.pickupPair.lat},${this.pickupPair.lng}`;
    var dest = `${this.dropoffPair.lat},${this.dropoffPair.lng}`;
    let miles;

    loader.load().then(() => {
      const service = new google.maps.DistanceMatrixService();

      service.getDistanceMatrix(
        {
          origins: [origin],
          destinations: [dest],
          travelMode: google.maps.TravelMode.DRIVING,
          unitSystem: google.maps.UnitSystem.IMPERIAL,
          avoidHighways: false,
          avoidTolls: false,
        },
        (response, status) => {
          if (status !== "OK") {
            alert("Error was: " + status);
          } else {
            const originList = response.originAddresses;
            const destinationList = response.destinationAddresses;

            this.mileage = response.rows[0].elements[0].distance.text;
            this.mileage = this.mileage.replace(" mi", "");
            this.getCost();
            resolve();// We are done, and calling function await will stop.
          }
        }
      );
    })

  })
}

// Full async/await
async function getDistance() {
  var origin = `${this.pickupPair.lat},${this.pickupPair.lng}`
  var dest = `${this.dropoffPair.lat},${this.dropoffPair.lng}`
  let miles

  await loader.load();

  const service = new google.maps.DistanceMatrixService()

  // If getDistanceMatrix is a promise and possible to await
  const response = await service.getDistanceMatrix(
    {
      origins: [origin],
      destinations: [dest],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.IMPERIAL,
      avoidHighways: false,
      avoidTolls: false,
    },
  )

  if (response.status !== 'OK') {
    alert('Error was: ' + status)
  }

  console.log(response.data)
}

【讨论】:

  • 如果我没记错的话,好像可以称为promise。
  • 尝试在调用前使用 await 而不是 .then。
  • 它实际上不能被称为promise,但是promise chaining的第一种方法效果很好!非常感谢您的帮助!
  • 太棒了!是的,有时第三方库支持这两种风格。承诺和回调。不幸的是,当他们只处理获取结果的回调方式时,您必须执行类似于我的第一个解决方案的操作。我基本上是在强迫一切成为一个承诺:)
猜你喜欢
  • 1970-01-01
  • 2018-05-19
  • 2020-06-24
  • 2020-06-14
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
相关资源
最近更新 更多