Having trouble generating JSON data within an asynchronous loop using Vuejs and FileReader?

A mechanism is required for users to submit multiple files through a Vue form component. Prior to sending the data to a remote JSON API endpoint, these files need to be processed.

An attempt was made to address this by utilizing FileReader and an asynchronous foreach loop in the following manner:

methods: {
  readerLoaded(geojson, date, post_data) {
    post_data.dated_profiles.push({
                  'date': date,
                  'geojson': geojson
                });
  },
  setupReader(file, date, post_data, readerLoaded) {
    var reader = new FileReader();
    reader.onload = function(e) {
      const result = JSON.parse(e.target.result);
      // Send result to callback
      readerLoaded(result, date, post_data);
    };
    reader.readAsText(file);
  },
  validate() {
    if ( this.$refs.form.validate() ) {
      /* Process GeoJSON files to POST data to API */
      const data = {
          'name': this.name,
          'index': this.index,
          'dated_profiles': Array()
      }

      const asyncLoopFunction = async (datasets, post_data, setupReader, readerLoaded) => {
        const promises = datasets.map(function (item) { return setupReader(item.file, item.date, post_data, readerLoaded); })
        return await Promise.all(promises)
      }

      asyncLoopFunction(this.datasets, data, this.setupReader, this.readerLoaded).then( () => {
        console.log('All async tasks complete!')
        console.log("After async", data)
        this.$store.dispatch('postProfile', data)
      });

    }
  }

The issue at hand involves passing the final JSON data object to a Vuex store action via dispatch, where the dated_profiles array ends up being empty.

  • Upon inspecting the JSON object after completion of the async loop, the browser console shows this
    Object { name: "foo", index: "1", dated_profiles: [] }
    . Although it appears empty, expanding it reveals the correct full array...
  • When attempting to send this data with the request, it asserts that the array is indeed empty. Isn't it supposed to wait for all promises to finish?

The reason behind the failure of my async/await combination remains unclear. Could you help pinpoint where I may have gone wrong?

Answer №1

When you pass this.setup_reader to the asyncLoopFunction, it seems like you meant to pass this.setupReader instead.

Furthermore, the setupReader method lacks a promise return type at the moment. It would be best to update it as follows:

setupReader(file, date, post_data, readerLoaded) {
  return new Promise((resolve, reject) => {
    var reader = new FileReader();
    reader.onload = function(e) {
      const result = JSON.parse(e.target.result);
      readerLoaded(result, date, post_data);
      resolve();
    };
    reader.onerror = () => reject();
    reader.readAsText(file);
  }
},

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

Tips for causing the JavaScript confirm alert to appear just a single time

My latest project involves creating a confirm alert that notifies users when their password is about to expire, prompting them to change it. The functionality for this alert is located in the header section of the website. Upon successful login, users are ...

Mapping keys in a react component for efficient sorting

I'm facing some challenges when attempting to reorder keys from a state within my map function in React.. The original output is: monday : {1200: {…}, 1500: {…}, 1800: {…}, 2000: {…}, 2200: {…}, 0000: {…}, 0100: {…}, 0500: {…}, 0600: ...

Oops! The "id" parameter is missing in the Vue-router router-link

I am currently working with Laravel 8 along with Vue 3, vue-router, and vue-loader. Inside the router/index.js file: import { createRouter, createWebHistory } from 'vue-router' import CategoryShow from '../components/category/CategoryShow&a ...

Error in Vue: Expected object but received a function instead of a valid value

I am attempting to apply a computed function to my style. However, the computed function uses a property within it and Vue is throwing an error stating that it expects an object but is receiving a function. Below is the code in question. <template> ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

When functions are sent to children of a react component, they do not inherit the context of the parent

I'm facing an issue while working with React where I am encountering difficulty passing a function from a parent component to multiple children components. The function calls other functions that are also housed within the parent component. Although ...

Can you display a popup on a leaflet map from beyond its boundaries?

Utilizing leaflet maps, I have implemented a functionality where clicking on the map opens a popup at a specified location and centers on that position. The code for this is as follows: var popup = L.popup(); function onMapClick(e) { popup . ...

A guide on including a node as a parameter, alongside other data types, in a function using ajax within Umbraco

When attempting to pass a node and two strings as parameters to a JsonResult in Umbraco, I encountered an issue where the node variable had no value when debugging the method. Below is the JavaScript code: function newsSub() { if(validateForm('ne ...

Running Node.js code from npm within Swift can be achieved by following these steps:

I am looking to integrate a Node JS package downloaded from npm into my Cocoa App and run it using Swift. Despite searching online, I have not been able to find any information on whether it is possible to call an npm package from Swift. Can anyone help m ...

The phantom stdout for Node 4.2.0 is showing an error with code NETWORK_ERR: XMLHttpRequest Exception 101. This error indicates that a network error

Executing the code below in node 4.2.0, it is triggered within a scheduled node cron job rather than through the terminal. The website being 'requested' is . module.exports.dynamicRequest = function(url, callback) { var makeDynamicRequest = fu ...

Having trouble getting Vue.js to cooperate with a brand new Laravel 5.8 setup?

I set up a fresh Laravel project using laravel new sample. Then I executed npm install followed by npm run dev. Next, I modified the welcome.blade.php file as shown below: <!DOCTYPE html> <html> <head> <script type="text/j ...

Tips for querying multiple elements that share a common ID and verifying if the input has been modified

I have a series of text inputs that share a common id prefix but differ slightly at the end. Whenever a user enters text in any of these input fields, I want to trigger a function. Currently, I have this functionality implemented with the following code: ...

Implementing JavaScript to provide personalized error messages for empty form fields

I am facing an issue with form validation on iPhone / Safari, as they do not recognize the required attribute. I want to display individual error messages below each empty input field using JavaScript. Although my code is functional, the problem is that t ...

How can I create walls in ThreeJS using a path or 2D array?

I am faced with the task of creating a 3D house model, specifically the walls, using a 2D path or array that I receive from a FabricJS editor that I have developed. The specific type of data being transferred from the 2D to 3D views is not critical. My in ...

Inspecting a substring of an element dynamically added in VueJs

When I click a button in my form, it adds a new line. The challenge is making sure that each new line evaluates independently and correctly. In this case, the task involves checking the first 2 digits of a barcode against a dataset to determine a match or ...

Converting JavaScript values to C# code behind: A step-by-step guide

I'm facing a challenge where I need to retrieve JavaScript values in the code behind using C#. While I am aware that I can achieve this using hidden fields, there are no server controls on the page for postback. Can someone please advise me on how to ...

Checking the strength of passwords containing special characters

I'm looking to enhance my password validation by including special characters. However, I'm running into an issue where using '%' is causing problems. How can I properly implement validation for special characters? $.validator.addMetho ...

The Access-Control-Allow-Origin CORS header does not align with the null value on the Ajax request

Encountering the same issue in my browser Cross-Origin Request Blocked: The Same Origin Policy prevents access to the remote resource at http://abc-test123.com/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’). My ...

Cropper.js, effortlessly populating a container with a perfectly centered image

I took inspiration from the cropper.js library website but made modifications. You can check out the original example here. Here's my version of the modified example: CodePen Link var image1 var cropper1 var image2 var cropper2 ...

Encountering a "Permission denied" error when attempting to load Firebase SDKs through a reserved URL

I have successfully deployed my Firebase site using a reserved URL following the documentation. Everything functions properly when my database rules are set to "true". However, when I try to implement a rule, it results in an error stating "Permission Deni ...