Vue- async function results in a Promise object with a status of <pending>

Hey everyone, I could use some assistance with my Vue code. Here's the issue:

I'm attempting to retrieve data (specifically anime) from an online anime API.

In my project, I have two files: Anime.vue (the view page) and getAnime.js (which houses the function). Initially, when the function was within Anime.vue, everything worked fine. However, after separating it into a different file, I'm now facing difficulties sending the anime data to the Vue page.

Below is the code snippet from Anime.vue:

<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 here's the content of getAnime.js:

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

Answer №1

Check out this code snippet:

async function searchAnime() {
  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 searchAnime

Answer №2

When using an async function, it automatically returns a Promise, so remember to use <code>await
when calling the function.

async function fetchAnime() {
  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;

To utilize this in your Vue file:

try {
  const animeData = await fetchAnime();
} catch(e) {
 // handle any errors here
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

``What is the best way to include a JavaScript jQuery variable value within a PHP array

Let's consider the following scenario: var folderName = jQuery.trim($('#dirname').val()); var parentFolder = jQuery.trim($('#parent').val()); var dynamicUrl = '<?=$this->url(array('controller'=>'index ...

How can I populate a dropdown list in JavaScript with JSON data from a file?

I am experiencing difficulties when it comes to parsing JSON files for use in a dropdown list. JSON: { "BD": "Bangladesh", "BE": "Belgium", "BF": "Burkina Faso", "BG": "Bulgaria", "BA": "Bosnia and Herzegovina" } The goal is to populate the dropdownlist ...

Using Backbone.js to Retrieve Data from the Server and Bind it to a Model

Having recently delved into Backbone.js, I found this informative tutorial quite helpful in getting started. Now, I am looking to take things a step further by fetching data from the server instead of hardcoding values in JavaScript as demonstrated in the ...

In what way can you establish a boundary for a border?

My goal is to create a 10x10 grid with randomly placed black boxes, but I am facing an issue in my game setup: https://i.sstatic.net/uKy06.png Currently, the 5 black boxes are generated randomly in a row, sometimes exceeding the border and breaking the c ...

Troubleshooting VueJS: Issue with $router.push and passing query parameters

In my NuxtJS(v. 2.10.2) application, there is a URL structure that includes the post's id like this: /post?pid=5e4844e34202d6075e593062. The URL works fine and loads the post based on the value of the pid query parameter. However, when a user adds ...

Prevent the border from shrinking upon being clicked

I'm currently working on customizing an accordion using jQuery for the animation effects. However, I am facing an issue where clicking on the accordion header causes the border around the plus sign to shrink in size as well. My goal is to only have th ...

Safari iOS 8 experiencing issues with loading WebGL image textures

The example mentioned above runs smoothly on all major browsers, including Safari on Mac OS. However, it fails to display the correct image on my iPad running the latest iOS 8. Click here for the example. Similarly, the tutorial provided in the following ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

Creating an Engaging Data Visualization: Blending Candlestick Insights with Line Graphs

I'm attempting to display a moving average on a candlestick chart, but I'm facing an issue where the path of the line is not fully appearing on the SVG canvas that I've created. I've searched through various posts to understand how to o ...

Error: Property cannot be read after page refresh or modification

Upon refreshing or running the project for the first time, I encounter the error: TypeError: Cannot read property 'statements' of undefined This issue is perplexing as the data renders correctly but it appears that the connection is failing. ...

Disable the default page scrolling behavior when collapsing an accordion section in Bootstrap 4 framework

Incorporating a Bootstrap 4 accordion with an expanded body section that causes the content below to scroll up when collapsed. To address this issue, attempting to scroll to the top of the clicked header and prevent undesirable scrolling from the collapse ...

I encountered a permission error while trying to npm install, despite running the command with root privileges

After running npm install as root, I am still encountering permission errors. This is unfamiliar territory for me. I have attempted using chmod -R 777 *, and chown nobody:nogroup -R * within the project folder, but to no avail. Here's the specific er ...

What is the process for interacting with a Node.js Web API using an Angular JS API?

Seeking assistance with converting HTML into JADE format, encountering issues with {{record.name}} not functioning correctly. This is preventing the fetching and printing of values. Below are the complete file details: Directory view can be seen here. JS ...

Enhance v-file-input with validation

How can I make sure that a file has been chosen using v-file-input and ValidationProvider from vee-validate? Check out the code below: <v-flex> <ValidationProvider rules="required" v-slot="{ errors }"> <v-file-inpu ...

Using node.js to send a response with response.writeHead on the http module

While working on my own custom http module, I stumbled upon a few confusing points while studying the official node.js http module api: When a user utilizes the response.writeHead(statusCode, [reasonPhrase], [headers]) function, are the headers suppose ...

Refreshing a component using a sibling component in React

Currently, I am delving into the realm of React and embarking on a journey to create a ToDo App. However, I've hit a snag while attempting to add a new task to the list. Despite successfully adding an item to the list upon clicking the add button, upd ...

Using ES6's object destructuring to set default values for nested parameters

Utilizing es6 object destructuring for supplying default parameters to a function. function mapStateToProps({ shops: { cakeShop: {}, pieShop: {} }) { return { CakeShopName: shops.cakeShop.Name, PieShopName: shops.pieShop.Name } } An issue ari ...

Obtain the child's identification number and include it in the parent element as an ARIA

I need assistance with a JavaScript (or jQuery) function to dynamically add an 'aria-labelledby' attribute to parent <figure> elements based on the ID of the <figcaption>. I have multiple images and captions set up in <figure>&l ...

Discover the secret to displaying v-text-field label text within the input using Vuetify

I would like the label to appear inside the input field. For reference, please see below: In version 2.4.9 of Vuetify, I have used the filled property and added CSS to create a border using the codepen link below: https://codepen.io/magooo/pen/JjELwrx .t ...

The checksum verification encountered an error during the installation process of the npm package weexpack

I am encountering an issue while trying to install weexpack. It seems that the sha1 checksum verification is failing. npm install -g weexpack npm ERR! code EINTEGRITY npm ERR! sha1-33w+1aJ3w/nUtdgZsFMR0QogCuY= integrity checksum failed when using sha1: w ...