在JavaScript中如何先完成数据赋值再执行后续代码?以Vue地理定位为例
根本原因
navigator.geolocation.getCurrentPosition 属于异步回调API,调用后不会阻塞后续代码执行,你在调用getLocation后立刻打印经纬度时,用于赋值的showPosition回调还没有被触发,所以拿到的永远是初始值。
另外你代码里存在多余写法:选项式API的data函数返回的属性本身默认是响应式的,不需要额外用ref包裹,直接写初始值0就可以。
解决方法:封装Promise配合async/await等待异步执行完成
我们可以把获取定位的逻辑封装成Promise,就能用await等待定位成功、赋值完成后再执行后续代码,改后完整代码如下:
<template> <button @click="start">Start</button> </template> <script> export default { data() { return { latitude: 0, longitude: 0 }; }, methods: { async start() { await this.getLocation(); // 等待定位完成、赋值结束再往下执行 console.log(this.latitude, this.longitude); // 此时已经能拿到更新后的经纬度 }, getLocation() { return new Promise((resolve, reject) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position) => { this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; resolve(); // 定位赋值完成后标记Promise成功 }, (error) => { // 可以在这里处理定位被拒绝、超时等异常情况 reject(error); } ); } else { alert("Geolocation is not supported by this browser."); reject(new Error("Geolocation not supported")); } }) } } }; </script>
其他可选方案
如果你不想改异步封装,也可以把需要定位完成后执行的逻辑,直接放到showPosition回调的末尾,也能保证执行时经纬度已经完成赋值。
内容的提问来源于stack exchange,提问作者aulia amirullah
相关产品推荐
相关产品推荐

