Home > Mobile >  Vue- async function returns Promise {<pending>}
Vue- async function returns Promise {<pending>}

Time:12-09

Okay so this is some basic Vue that I'm having difficulties with:

I'm trying to fetch some data (anime) from an anime API which was available online

I have Anime.vue (which is the view page) and getAnime.js (which contains the function). When I had the function in the Anime.vue file it worked but I tried to separate it and now I can't send the anime the vue page. Here's the code:

Anime.vue (only included the script part)

<script>
import getAnime from "../composables/getAnime";
export default {
  data() {
    return {};
  },

  setup() {
    let anime = getAnime();

    console.log(anime); //this returns Promise pending on console
  },
};
</script>

and this getAnime.js file:

async function getAnime() {
  const axios = require("axios");
  let anime = ''

  try {
    const response = await axios.get("https://api.jikan.moe/v3/anime/"   20)
    .then((res) => {          
        anime = res.data
        console.log(anime) //this returns the anime file as {request hash...
       })
 } catch (error) {
    console.log(error);
  }
  return anime
}
export default getAnime

CodePudding user response:

try this:

async function getAnime() {
  const axios = require("axios");

  try {
     const response = await axios.get("https://api.jikan.moe/v3/anime/"   20);
     return response;
  } catch (error) {
     console.log(error);
  }
}
export default getAnime

CodePudding user response:

async function returns a Promise implicitly, so you need to await the result.

async function getAnime() {
  const axios = require("axios");

  try {
     const response = await axios.get("https://api.jikan.moe/v3/anime/"   20);
     return response;
  } catch (error) {
     console.log(error);
     throw error;  
  }
}
export default getAnime;

In your vue file :

try {
  const animeData = await getAnime();
} catch(e) {
 // handle errors
}
  • Related