LoginSignup
0
0

More than 1 year has passed since last update.

asyncで取得したデータがpromiseから取り出せない時。

Posted at

vue.jsで以下のようにしてLaravelが発行するJsonと連携を試みていて、どハマりしました。

import axios, {AxiosResponse} from "axios";

export default {

~~~ 中略 ~~~

  data() {
    return {

~~~ 中略 ~~~
  , mounted: function () { // ここが間違ってた
    let items;

      items = await this.fetchEvents();
      console.log(items); // 中身が欲しいのにPromise<pending>が返ってくる。

  }
  , methods: {
    fetchEvents: async function () {

      const response = await axios.get('http://localhost:3000/api/get-events-from-google-calendar');
      return response.data.items;
    }
  },
}
</script>

awaitはasyncの中に置かなければいけない、というところまでは把握していましたが、その関数を呼んでいる側も asyncでないといけない事に気づいていませんでした。

なので、上のコードのmountedのところは下のように宣言しないとasyncで囲われていることになりません。

, mounted: async function () { // ここが間違ってた

もしくはmountedないで、即時関数使って

async () => ({この中で await this.fetchEvents(); }()) 

みたいにして、asyncにする。処理の初めから非同期を止めたいところまで囲い切らないと効かない。
考えてみれば当たり前ですが日頃コピペでPromiseを乗り切っていると、ちょっと関数に切り出すだけでもハマります。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0