Async/Await 在 Vue 中使用 mount() 钩子不工作

Async/Await in Vue with mount() hook not working

我正在使用 vue 2.5,我有一个挂载挂钩,它调用一个模块,该模块获取一个 API nedpoint 并通过挂载挂钩 return 将其发送到 vue 组件。我之前曾问过问题并被引用 post return response from async call 并在回答中遵循了示例,但我的 Vue 组件变量在组件呈现时仍然显示为未定义。这是我的代码:

/modules/retrieveLeagueLeaders

 const getLeagueLeaders =  (url, params) => {
    fetch(url + new URLSearchParams(params), {
      method: "get",
      headers: {
        Authorization:
          "Basic ****=",
      },
    })
      .then((response) => response.json())
      .then((data) => {
        let leagueLeaders = data;
        console.log(
          "leagueLeaders is %s",
          leagueLeaders.cumulativeplayerstats.playerstatsentry[0].player
            .LastName
        );

        return leagueLeaders;
        
      });

    
  };

  module.exports = getLeagueLeaders;

和 Vue 代码:

/src/components/leagueLeaders
 mounted: async function () {
      this.qbLeaders = await getLeagueLeaders(this.fetchQbUrl, this.params);
      console.log("qBLeaders is %s", this.qbLeaders);
    },
  })

控制台显示

qBLeaders is undefined nflLeagueLeaders.js:28
leagueLeaders is Wilson getLeagueLeaders.js:17

我已经尝试将整个模块包装在一个 Promise 中,但在 运行 时它仍然没有 return 一个 promise。我在 Vue 挂载挂钩中使用 Async/Await 的方式有什么不正确的地方吗?我真的可以使用一些指导,因为我已经尝试了 posts 中的所有建议都无济于事。提前致谢..

不要尝试 return 回调中的值,这是行不通的,您可以简单地 return 承诺 :

const getLeagueLeaders =  (url, params) => {
   return  fetch(url + new URLSearchParams(params), {
      method: "get",
      headers: {
        Authorization:
          "Basic ****=",
      },
    })
      .then((response) => response.json())
         
  };

  module.exports = getLeagueLeaders;