Vue - receiving the output of a synchronous function

I'm having difficulty displaying the synchronous results of the method provided below.

I am invoking the method from another method:

var result = this.getVendor(id)
console.log(result)

Below is the fetch method code:

methods: {
    async getData(id) {
          const response = await fetch(`${API_URL}api/${id}`, {
            method: "GET",
            headers: {
              authorization: `Bearer ${localStorage.token}`
            }
          })
            .then(res => res.json())
            .then(data => {
              return data;
            });

          await response;
        }
}

What is the best way to return the response results from the getData() function in order to display it in the console?

Answer №1

Async functions Always result in a promise being returned.

One can utilize the await syntax to ensure it is returned correctly.

    async fetchData(id) {
          const response = await fetch(`${API_URL}api/${id}`, {
            method: "GET",
            headers: {
              authorization: `Bearer ${localStorage.token}`
            }
          })
           const data = await response.json()

           return data
        }

The data can be accessed outside of the function wherever it is invoked.

let data = null
object.getData(2)
.then(x => {
data = x
})

Furthermore, when utilizing async await, it is crucial to implement try and catch blocks to handle any potential errors.

    async fetchData(id) {
       try {
          const response = await fetch(`${API_URL}api/${id}`, {
            method: "GET",
            headers: {
              authorization: `Bearer ${localStorage.token}`
            }
          })
           const data = await response.json()

           return data
        }
      } catch(err) {
    console.error(err)
    }

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

JavaScript code to convert a query into an array

Is there a way to search through a JavaScript array to find all names that start with the letter A? If so, how can I display all of the information associated with those names? Name":"Albert","age":"14" Name":"Alison","age":"14" Here is my JSON array: ...

Determine the precise location of a screen element with jQuery

Can anyone help me determine the precise position of an element on the current visible screen using jQuery? My element has a relative position, so the offset() function only gives me the offset within the parent. Unfortunately, I have hierarchical divs, ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

Swap information in one array with information from a different array

I am working with two arrays: const data = [ { id: 0, identifier: 'free-2020', name: '<I18nText id="pricing.plans.name.free" />', planTitle: 'free', price: '00', ...

Jquery Autocomplete has the ability to store and recall previous user selections

When the region is selected, autocomplete addresses should be displayed. Each time the region changes, the Jquery autocomplete function is called. While I am able to get the correct autocomplete addresses for the current region, I also receive address list ...

Error message 'Object doesn't have support for this property or method' is triggered by a basic JSON object

Recently, I developed a compact framework for loading resources asynchronously (hyperlink). The framework functions properly in modern browsers such as Opera, Chrome, and Firefox. However, when testing it in IE8, the code fails to execute. Internet Explor ...

Retrieval of jQuery remove() method

Essentially, I am utilizing an OnClick function to delete a DIV. Once the OnClick is triggered, it invokes the remove() jQuery function to eliminate the div. Below is my code that implements the removal using remove(): <div id="add"> <button typ ...

Adjust the package.json file for deployment

I've encountered a problem while attempting to deploy my nodejs application on Heroku. Despite following the documentation and modifying files in the root directory, I have not been successful. Below is the structure of my package.json file: { ...

What is the best way to connect my products on an ecommerce site with hundreds of images?

Despite thoroughly searching the internet, I have been unable to find a solution to my dilemma. I am creating a platform that showcases a lengthy list of products on the website. Additionally, I have a database of pictures stored locally that need to be ...

Reducing Image Size in JavaScript Made Easy

I need help with a project where I want the image to shrink every time it's clicked until it disappears completely. I'm struggling to achieve this, can someone assist me? Here is the HTML code I have: <html lang="en" dir="l ...

Tips for maintaining previously accessed data when utilizing useQuery

I am currently working on incorporating a GET request using useQuery from the react-query library. Below is the relevant code snippet: import queryString from "query-string"; import { useRouter } from "next/router"; const { query } = ...

Can you explain the distinction between the terms "vite" and "vite preview"?

I recently created a project template with the help of vite. While looking through my package.json file, I noticed the following section; "scripts": { "dev": "vite", "build": "vue-tsc --noEmit &&a ...

MUI Tutorial: Displaying Text with Line Breaks

Whenever I input text into the MUI Textfield, it displays without any line breaks. Is there a more effective solution available? <Stack direction="row" alignItems="start" justifyContent="start" mb={5}> <TextFie ...

Selenium is detecting a textbox as hidden, despite it being visible in the browser on my end

My password textbox code is as follows: <input class="blahblah" id="someId" type="password"></input> While I can manually interact with this textbox in the browser, when attempting to automate testing using selenium, an error is thrown sayin ...

How to populate an ExtJS 3.4 combobox with local JSON data in a few simple steps

I am utilizing ExtJS 3.4 and in need of populating a combobox with specific data obtained from a previous XMLHttpRequest, stored in a variable as follows: my_variable = "[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","no ...

What is the best way to implement my custom toolbar button to utilize the form's validation function within react-admin?

I have developed a unique Toolbar with a custom button that is supposed to mimic the behavior of the standard SaveButton but also perform additional actions after the form is submitted. The form should only be able to submit if it passes validation, and an ...

Issue with my JavaScript code for customizing checkboxes: the else condition is not being triggered

I'm currently in the process of customizing my own version of "checkboxes" by styling label elements and moving the actual checkbox off-screen. This is the approach I decided to take based on the design and functionality requirements presented to me. ...

Issue with handling promise rejection of type error in node.js

Whenever I try running node server.js in Node.js, an error message pops up saying 'Cannot read property 'length' of undefined'. Despite installing all the necessary libraries (such as request) and browsing through various related posts ...

"Utilize jQuery to create a new row when an image button is clicked

I am looking for a way to duplicate the existing <tr> every time I click on the + button, represented by <i class="fa fa-plus" aria-hidden="true"></i> Here is the structure of my <tr>. How can I achieve this using jQuery or JavaScr ...

What is the method for enabling or disabling a text field based on the chosen value in a b-form-select?

Can anyone assist me with enabling or disabling an input text field based on the values selected in a b-form-select element? Your help would be greatly appreciated. ...