首页 > 解决方案 > 另一个异步函数中的异步函数

问题描述

我对此感到惊讶,因此希望获得一些关于我在使用 Async Await 语法时做错了什么的指导。

'getUserLocation' 函数返回用户的位置:

  getUserLocation = async () => {
    const response = await window.navigator.geolocation.getCurrentPosition(
      coord =>  ( coord.coords),
      err => {
        const { code, msg } = err;
        if (code === 1) {
          prompt(
            "Location is needed to get the local salah time, please try again.",
            msg
          );
        } else if (code === 2 || code === 3) {
          prompt(
            "Sorry, something went wrong, please try again or try again later.",
            msg
          );
        }
      },
      {
        enableHighAccuracy: true,
        timeout: 5000,
      }
    );
    // this.setState({
    //   userLocation: response,
    // });
    return response;
  };

  fetchTimes = async () => {
    const { userLocation, method, month, year } = this.state;
    const { lattitude, longitude } = userLocation;
    if (!lattitude) {
      let ress = await this.getUserLocation();
      console.log("ress: ", ress);
      const url = `http://api.address?latitude=${lattitude}&longitude=${longitude}&method=${method}&month=${month}&year=${year}`;
      console.log("url:", url);
      const resp = await fetch(url);
     ....

然而,即使使用 'await' 关键字调用了 'getUserLocation ,控制台仍报告fetch在提示用户访问位置之前进行了调用,并且该位置返回给 fetchTimes 函数。getUserLocation为什么在继续呼叫之前不等待先返回位置fetch

谢谢

标签: javascriptasynchronousasync-awaitgeolocationfetch

解决方案


推荐阅读