Vue.js, when using async await functions, sometimes renders blank results

Currently working on a JavaScript project that requires the use of await/async to fetch data from an API.

Here is a snippet of my code:

        const fetchData = async () => {
          let data = [];
          for (let i = 0; i < this.data.length; i++) {
            const formData = new FormData();

            const fetchLogs = () => {
              getData.request(new URLSearchParams(formData), (response) => {
                if (response.status >= 200 && response.status < 300) {
                  console.log('Data response:', response);
                  return response.data.data;
                }
              });
            };

            let logsData = await fetchLogs();
            console.warn(logsData);
            data.concat(logsData);
          }

          return data;
        };

However, the issue I'm facing is that the logs are being returned before the response is received.

myBabelConfig.js

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        useBuiltIns: 'usage',
        corejs: 3.6,
        modules: false,
      },
    ],
  ],
};

"vue": "^2.6.0"

Can you spot what I might be doing wrong in this setup?

Answer №1

Avoid running the callback function of the request and instead simply return the response :

 const fetchLogs = async () => {
          let response = await getLogs.request(new URLSearchParams(formData));
            if (response.status >= 200 && response.status < 300) {
                  logData('getLogs', response);
                  return response.data.data;
                }
            };

            let logData = await fetchLogs();

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 process for updating JSON using TextFields?

I am currently facing an issue with my TextFields displayed within a material-ui dialog. These TextFields are initially populated by JSON data, which you can see in the example below. The problem is that once the TextFields are populated, I am unable to up ...

Modify the form's action attribute when submitted

I am trying to create a form with multiple buttons that will change the action and target properties when a specific button is clicked. Below is my code snippet: <div id="root"> <form :action="form.action" ref="form" :target="form.target"&g ...

Ways to retrieve object in Javascript

I retrieved this data object from a JSON file source. { "Apple": "Red", "Orange": "Orange", "Guava": "Green", } Afterward, I transformed it into an Object using: var data = JSON.parse(dataFromJson); which resulted in a JavaScript object ...

Tips for toggling the appearance of like and add to cart icons

I am attempting to create a simple functionality for liking and adding items to a cart by clicking on the icons, which should immediately change the icon's color when clicked. However, I am facing an issue where the parent div's link is also bein ...

Creating a hover effect for a specific card while maintaining the rest of the cards unaffected

When hovering over a card, all icons are displayed instead of just the icons for that specific card. I want to show only the icons for the card being hovered on (example output: image). The cards are generated automatically using v-for and fetching data fr ...

Customizing the path of your nuxt.js router: A comprehensive guide

I have a software development marketing site with over 30 landing pages that I want to organize in the ./pages/landing folder. Currently, the files inside ./pages/landing can be accessed through URLs like: www.example.com/landing/python-development-expert ...

What is the proper way to utilize $location within a standard function?

I am working on an Angular app that consists of both AngularJS and plain JavaScript such as Ajax. I am trying to figure out how to use $location within a function without passing it as a parameter. function x() { $location.path('/error').repl ...

Swap out a module with a different one in a node.js environment

In the scenario where a node.js application consists of numerous files referencing a particular module (like underscore), and there is a need to replace that module with another (such as lodash), the typical approach involves globally replacing the names a ...

Creating a sticky popup feature for your Chrome extension

Just starting out with chrome extensions and looking to create one that appends an external class to a selected tag. For example, let's say we have the following tag: <h1>extension</h1> When the user clicks on this element, I want to ad ...

Unable to turn off X-Powered-By: Express

After attempting to use app.disable("x-powered-by"); without success, I came across some helpful posts on the topic: how to remove X-Powered-By in ExpressJS Can't get rid of header X-Powered-By:Express I am using "express": "^4.16.4" as backend a ...

Trouble uploading an audio blob as a base64 string using Google Drive API with the drive.files.create method - File ID could not be located

My current challenge involves sending an audio blob to a specific Google Drive folder. To accomplish this, I convert the blob into a file before initiating the transfer process. However, I have encountered an error from the beginning: Error: File not fo ...

Executing a JavaScript function through a hyperlink created by an AJAX request

Having a JavaScript function here. I am performing an AJAX call, and within the received content, there is a link that needs to trigger the JavaScript function. MyJavascriptFunction(bla){ alert (bla); } ...

Received an empty response while making an AJAX request - ERR_EMPTY_RESPONSE

I am trying to fetch real-time data from my database using Ajax, but I keep encountering an error. Here is the code snippet: <script> window.setInterval( function() { checkCustomer(); //additional checks.... }, 1000); function che ...

Transfer an array via Ajax to a Python server script

I need to send the names, values, and labels of my form elements when a button is clicked. Since the submit button messes up the order, I decided to handle it with JavaScript: $('#mybutton').click(function() { m.modal('show'); ...

Comparing Weex components: <list> versus <recycle-list>

Currently, I am working on a Weex application using Vue.js. My main focus is on creating a list component and while going through the documentation, I came across two components that caught my attention: <list> <recycle-list> I'm curio ...

Loop through a JSON object within the collection of another ng-repeat loop

I'm facing an issue with my ng-repeat loop where I iterate through a JSON and display it in a table. The problem is that when I try to iterate through a nested JSON value, it's treating it as a string. <tr ng-repeat="(key,value) in event. ...

Combining cells through the utilization of JavaScript

I've searched for ways to merge cells in a table using JavaScript but haven't been able to find any code that works. Is there a specific approach I can follow to implement cell merging like in MS-WORD tables? Your advice would be greatly apprec ...

Performing the task of removing a complete script using D3 or JavaScript

Here is the current setup I have in my code: The index.html file contains <div id="div1"></div> and I dynamically load a file into it (when a socket arrives) using this script: <script> var socket = io.connect('http://127.0. ...

What is the method for configuring Vue to utilize a value other than the value property in form fields?

I am facing a unique challenge. Consider this: <select name="screw[type]" v-model="form.screw.type"> <option value="My value" ><?php _e('My value', 'fiam'); ?></option> //[...] Now, in another part of my ...

Manipulate Angular tabs by utilizing dropdown selection

In my latest project, I have developed a tab component that allows users to add multiple tabs. Each tab contains specific information that is displayed when the tab header is clicked. So far, this functionality is working perfectly without any issues. Now ...