【问题标题】:How can I set some data before executing another code in javascript?如何在 javascript 中执行另一个代码之前设置一些数据?
【发布时间】:2021-10-30 18:13:06
【问题描述】:

我正在尝试在执行另一个代码之前先设置我的地理位置数据。事实证明,如果我这样做,它会给我初始数据。有没有办法等待第一个代码执行完毕,数据可用后,我可以执行第一个代码下面的代码?

<template>
  <button @click="start">Start</button>
</template>

<script>
  import { ref } from "vue";

  export default {
    data() {
     return {
       latitude: ref(0),
       longitude: ref(0)
     };
    },
    methods: {
      start() {
        this.getLocation(); // execute this first
        console.log(this.latitude, this.longitude); // execute this after the data is updated
    },
    getLocation() {
            if (navigator.geolocation) {
              navigator.geolocation.getCurrentPosition(this.showPosition);
            } else {
              alert("Geolocation is not supported by this browser.");
            }
      },
  showPosition(position) {
     this.latitude = position.coords.latitude;
     this.longitude = position.coords.longitude;
  },
};
</script>

【问题讨论】:

  • 使用像 await this.getLocation(); 这样的承诺。 getLocation 函数应该返回在设置纬度和经度时解析的新 Promise。

标签: javascript vue.js vuejs2 async-await vuejs3


【解决方案1】:

两件事:

  1. this.getLocation()返回一个Promise
  2. start() 转换为async start(),以便您可以在函数中使用await 关键字
export default {
  data() {
    return {
      latitude: ref(0),
      longitude: ref(0),
    };
  },
  methods: {
    async start() {
      const success = await this.getLocation(); // execute this first
      if (success) {
          console.log(this.latitude, this.longitude); // execute this after the data is updated
      } else {
          alert("Geolocation is not supported by this browser.");
      }
    },
    getLocation() {
      return Promise((resolve) => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(pos => {
            this.showPosition(pos);
            resolve(true);
          })
        } else {
          resolve(false)
        }
      });
    },
    showPosition(position) {
      this.latitude = position.coords.latitude;
      this.longitude = position.coords.longitude;
    },
  },
};

【讨论】:

  • 它不起作用。这与我不使用 promises 和 async-await 的方式相同。第二次单击按钮时,数据会更新。第一次对更改数据没有任何影响。我想知道为什么第一次点击没有更新数据。
  • 啊,我的错,我犯了错误。给我一秒钟。
  • @auliaamirullah 现在已修复。
  • if (navigator.geolocation) { - 如果为 false,这将导致待处理的承诺
  • @EstusFlask 已修复。
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多