You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

await语法异常:位置权限请求异步流程未等待结果问题

Fixing Async/Await for Location Permission & Geolocation

It looks like the core issue here is that your code isn’t properly waiting for the location permission request to resolve before checking the answer variable. The nested promise chains are causing subsequent logic to run before the permission result is available, leading to answer being undefined when you try to use it.

Why Your Current Code Fails

  • The locationAccuracy.request() call returns a promise, but you’re not waiting for it to finish before moving to the next then() block.
  • The outer then() (after canRequest()) executes right after canRequest() resolves—not after the permission request completes. This means this.answer hasn’t been set yet when you check it.

Corrected Code Using Proper Async/Await

Since your function is already marked async, we can refactor it to use await for every asynchronous operation, ensuring each step completes before moving to the next:

async locationReq() {
  try {
    // Wait for the canRequest check to finish
    const canRequest = await this.locationAccuracy.canRequest();

    if (canRequest) {
      // Wait for the permission request to resolve
      const success = await this.locationAccuracy.request(
        this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY
      );

      // Set answer based on the user's response
      if (
        success.message === this.locationAccuracy.SUCCESS_USER_AGREED ||
        success.message === this.locationAccuracy.ERROR_USER_DISAGREED
      ) {
        this.answer = true;
      } else {
        this.answer = false;
        alert("Hiba történt. Kérlek próbáld újra!");
      }
    } else {
      // If we can't request permission, explicitly set answer to false
      this.answer = false;
    }

    console.log(this.answer);

    if (this.answer === true) {
      console.log("answer is true");
      // Wait for the platform to be ready
      await this.plt.ready();

      // Create and present the loading spinner
      const loader = await this.loadingCtrl.create({
        content: "Helyadatok lekérdezése..."
      });
      await loader.present();

      const options = { timeout: 15000 };
      try {
        // Wait for geolocation data to load
        const resp = await this.geolocation.getCurrentPosition(options);
        this.lat = resp.coords.latitude;
        this.lang = resp.coords.longitude;
      } catch (error) {
        // Handle geolocation failure
        this.lat = 47.49801;
        this.lang = 19.03991;
        this.presentToast();
      } finally {
        // Always dismiss the loader, whether success or failure
        await loader.dismiss();
        this.mapLoadingPresent();
      }
    } else {
      console.log("answer is no or undefined");
    }
  } catch (error) {
    // Catch any unexpected errors in the entire flow
    console.error("Location request error:", error);
    alert("Hiba történt. Kérlek próbáld újra!");
  }
}

Key Improvements:

  • Replaced all .then() chains with await to enforce sequential execution, so each step waits for the previous one to finish.
  • Added try/catch blocks to handle errors gracefully (async/await relies on try/catch instead of .catch() for error handling).
  • Explicitly set this.answer = false when canRequest is false to avoid undefined values.
  • Used a finally block to ensure the loading spinner is always dismissed, even if geolocation fails.
  • Awaited every asynchronous operation (like creating/presenting the loader) to prevent race conditions.

This refactor ensures your code waits for the user’s permission response before proceeding to geolocation logic, so this.answer will always be properly defined when you check it.

内容的提问来源于stack exchange,提问作者user3551399

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:48:54