Guide on using JSZip and VUE to handle an array of promises and store them in a local variable

My lack of experience with async functions has me feeling a bit lost right now... I'm attempting to loop through files in a folder within a zip file using JSZip, store these files in an array, sort them, and then save them to a local variable for further use.

Below is my code where I extract an array of promises:

async extractTests(file){
  let Zip = new JSZip();
  let tests = await Zip.loadAsync(file).then((zip) => {
      const promises = [];
      zip.folder("tests").forEach(async function (relativePath, file) {
        promises.push({ name: relativePath, data: await zip.file("tests/" + relativePath).async("text") });
      });
      return promises;
    })
  return tests;
}

Next, I attempt to sort the array in an event function triggered when a zip file is added:

extract(event) {
  const file = event.target.files[0];
  let res = this.extractTests(file);
  res.then(function (r) {
    res.sort(function (a, b) {
      var nameA = a.name.toUpperCase();
      var nameB = b.name.toUpperCase();
      console.log(a.name);
      if (nameA < nameB) {
        return -1;
      }
      else {
        return 1;
      }
    });
  })
}

The reason for sorting the list is because it's currently getting resolved in the wrong order - I suspect the sort function isn't even firing. It seems like it may be related to an asynchronous function. Sorting would be easier on a local variable, so I'm looking for guidance on how to achieve that and resolve the promises.

Appreciate any help!

Answer №1

Avoiding the use of async / await in higher-order functions is strongly advised, as it can result in unpredictable behavior where your code may appear to be functioning correctly but actually only triggers certain asynchronous calls without producing the desired output.

While I do not have access to the same library's file structure to replicate the issue, you could attempt modifying your extraction function in the following way:

async function extractTests(file: any) {
  let Zip = new JSZip();
  let tests = await Zip.loadAsync(file)
    .then((zip) => {
      const promises = [];
      zip.folder("tests")
        .forEach(function (relativePath, file) { // async function removed
          promises.push(
            zip.file("tests/" + relativePath)
              .async("text")
              .then((data) => { // Promise fulfillment data update implemented
                return { name: relativePath, data: data }
              })
          );
        });
      return promises;
    })
  return Promise.all(tests); // All promises resolved concurrently
}

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

sending the express application to the route modules

Currently, I am developing an express 4 api server with no front end code. Rather than structuring my project based on file types such as routes and models, I have decided to organize it around the business logic of the project. For example, within my Use ...

Filter search results using selected region from dropdown menu

I have been attempting to retrieve the value from a dropdown list and customize the search functionality specifically for the selected field. The client should only be able to search within the chosen zone in the dropdown. I have been searching for a solut ...

dynamically assigning a style attribute based on the dimensions of an image retrieved from a URL

My aim is to determine whether or not I should use an image based on its dimensions. To achieve this, I came across a function on stack overflow that can retrieve the dimensions of an image just by using its URL. Here is the code snippet they provided: f ...

Updating the Navigation Bar and Theme in CRM Dynamics 2013 to Reflect Your Organization's Branding

In my CRM Dynamics 2013 setup, I am faced with a unique challenge. I need to customize the Organization navigation bar based on which organization is currently loaded. Specifically, I have two organizations - QA and PROD. When a user switches to the QA org ...

Creating a reusable function for making HTTP requests in Angular

I have a scenario in my controller.js where I need to make an HTTP GET request when the page loads and when the user pulls to refresh. Currently, I find myself duplicating the $http code. Is there a way to refactor this for reusability? I'm struggling ...

Firebase Cloud Functions - Deleting the eldest offspring

I have created an onWrite cloud function that listens for updates made by a user. My goal is to delete the oldest child if there are more than three children present in the database. Here's where I currently stand: exports.removeOld = functions.datab ...

Enhance your UI experience with a beautifully styled button using Material-

I was using a Material UI button with a purple background. <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', heig ...

Convert a JSON Object using AngularJs

Is there a method in Angular to restructure this JSON Object? I am looking to convert the JSON object from its original format: $scope.TestJson = { "filters": [ { "dataPropertyID": "VoidType", ...

Padding-left in InfoBox

Currently, I am in the process of developing a map using Google Maps API3 along with the InfoBox extension available at this link I have successfully implemented an overall padding to the Infobox using the following code snippet: var infoOptions = { disa ...

Show brief tags all on one line

This image showcases the functionality of the site, specifically in the "Enter a code" column where users can input data using TagsInput. I am seeking to enhance this feature by ensuring that shorter tags are displayed on a single line. While I am aware th ...

Steps for obtaining a result from an asynchronous function once the stream has been closed

I'm having trouble with a download function that should return a promise with the filename as a result, but it is returning 'undefined' const fs = require('fs'); const https = require('https'); const path = require(' ...

Empty Angular-chart.js Container

How can I resolve the issue of getting a blank div and no output while trying to display a chart where the options, labels, and other data are initialized in the TypeScript controller and then used on the HTML page? I added the angular-chart.js library us ...

Tips for setting up bidirectional communication with props in a Vue.js component

Within my Vue.js component, I am utilizing the "name" props obtained from the parent component. My goal is to establish a two-way communication between the parent and child components using this props. The parent component code looks like this: <script ...

Randomly generated numerical value in input field

How can I generate a 15-digit number using JS code and then reduce it to just 5 or 6 digits in a text box? <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script type="text/javascript ...

The function 'transformArticles' is not recognized as a property of the object 'Article'

I'm encountering an issue with Typescript that I need help understanding. In my code, I have a route where I am importing a class called Article like this: import { Request, Response } from "express"; const appRoot = require("app-root-path"); import ...

Retrieving Gravity Forms AJAX Confirmation Message programmatically in JavaScript instead of displaying it

I have set up the Gravity Forms plugin in my Wordpress website and implemented the AJAX feature on my form. Currently, upon submission, a Confirmation message is displayed automatically. However, I am interested in retrieving the content of this message us ...

Error encountered with the item properties in vue-simple-calendar 'classes'

For my Vue.js project, I am utilizing the npm calendar package called `vue-simple-calendar` and aiming to implement dynamic classes for each event item like background-color, etc. However, the `classes` property doesn't seem to be functioning as expec ...

Locate the nearest date (using JavaScript)

Searching for the nearest date from an XML file. <?xml version="1.0" encoding="UTF-8"?> <schedule> <layout fromdt="2014-01-01 00:00:00" todt="2014-01-01 05:30:00"/> <layout fromdt="2014-02-01 00:00:00" todt="2014-01-01 05 ...

Can anyone suggest a method for adding comments and improving the organization of a bower.json file?

Managing a large project with numerous bower dependencies can be challenging. It's often unclear whether these dependencies are still being used or if the specified versions are necessary for a reason. It would be ideal to have the ability to add comm ...

Modify hyperlink address according to chosen option

Looking to incorporate a select input in Laravel using the latest alpine.js build. Here's what I have in mind: {{ Form::select('dogs', $dogs) }} This utilizes LaravelCollective HTML for streamlined form creation. Once an option is chosen, ...