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

What is the process for importing a jquery plugin like turnjs into a React component?

After searching through countless posts on stackoverflow, it seems like there is no solution to my problem yet. So... I would like to integrate the following: into my react COMPONENT. -I attempted using the script tag in the html file, but react does no ...

JavaScript does not function properly with dynamically loaded content

Trying to load the page content using the JQuery load() method. See below for the code snippet: $(window).ready(function() { $('#content').load('views/login.html'); }); .mdl-layout { align-items: center; justify-content: center ...

Change the color of the border to match the background color

I have a parent container with a unique background color. Inside the parent container, there is an unordered list (ul) with multiple list items (li), each having a distinct color and a brighter border color. Now, I am looking to extract the border color of ...

What is the process of transforming a string into an angular binding?

I have a variable called message that contains the text "you are moving to {{output.number}}". I attempted to insert this into a div element using $("#message").html(message); However, it just displayed the entire string without replacing {{output.number ...

I want to create a custom jQuery slider totally from scratch

Greetings everyone, I have been tasked with creating a slider using only HTML / jQuery code. Here is the template: And here is the HTML code for the template above: <div id="viewport-container"> <section id="sliding-container"> & ...

Turn off all animations for a specific div or HTML page

Whenever I add an item to a div, there's this strange flashing animation happening. It's like a blink or flash that updates the div with new data. I'm not entirely sure if it's a jQuery animation or not. Is there any way to disable all ...

My search field in Safari (desktop) doesn't respond to jQuery's .focus() function

My website has a hidden search field that appears when the user clicks on the search icon. I want to automatically bring focus to the search input so users do not have to click twice. This feature works perfectly in Chrome, but not in Safari (desktop). I t ...

Display a button in a single row table

Here is my table markup: <table class="table table-condensed"> <thead> <tr> <th>id</th> <th>task</th> <th>date</th> </tr> </thead> ...

Using a custom attribute in jQuery allows conditional statements to be executed using the

I have been attempting to create an if/else statement in jQuery using a custom attribute called "data-id". I decided to name it this way because I thought I could utilize the .data() method in jQuery, but unfortunately, it did not work as expected. Below ...

Jasmine - What is the best way to simulate a finally block?

After creating a controller in my test, I encountered an issue with the updateActionList function... this.createScope = function(scope) { if (scope) { this.scope = scope; } else { this.scope = $rootScope.$new(); } this.contro ...

Unlock the potential of Bootstrap 4 in Vue.js 2 without the need for bootstrap-vue

I'm interested in finding a way to incorporate bootstrap 4 into my vue.js 2.6 framework. Despite the abundance of tutorials available, many of them are outdated as of late 2020, or they insist on using bootstrap-vue, which introduces unwanted addition ...

vue-chartjs is experiencing difficulties when it comes to showing the labels and datasets

I'm having an issue with my line-chart. The data from the api/controller isn't showing up on the chart, even though the response contains all the data. https://i.stack.imgur.com/PWZxZ.png As shown in the image, the line-chart is empty but the r ...

The error message "The useRef React Hook cannot be invoked within a callback function" is displayed

I'm currently working on developing a scroll-to feature in Reactjs. My goal is to dynamically generate referenced IDs for various sections based on the elements within an array called 'labels'. import { useRef } from 'react'; cons ...

Combining Laravel with Vue: Organizing Routes in web.php and api.php Files

Hey there, I'm relatively new to Laravel and currently working on a project. I would really appreciate some advice on choosing the right architecture. My approach involves utilizing Vue for the front end and Laravel for the back end. Currently, I am ...

Vue recalculate computed value only when result changes

Let's dive into a simplified version of the problem at hand: export default { data () { return { i_change_alot: 0, }; }, mounted() { setInterval(() => { this.i_change_alot = Math.random(); ...

Using AngularJS and ServiceStack webservice, perform the "get('url')" operation

I'm completely new to AngularJS and I'm attempting to retrieve some JSON items from a webservice I quickly set up using ServiceStack. When I enter the URL in the browser, I can see the JSON object without any issues. However, for some reason Angu ...

What could be the reason for my Angular website displaying a directory instead of the expected content when deployed on I

My current challenge involves publishing an Angular application to a Windows server through IIS. Upon opening the site, instead of displaying the actual content, it shows a directory. However, when I manually click on index.html, the site appears as intend ...

Sketch a variety of numerical values in a circular formation

I was working on a number circle using the below fiddle, but I need it to always start from 0 at the top. How can I achieve this? Additionally, I would like to connect the numbers from the inner circle border to the number with a dotted line. How can I dr ...

There was an error because the variable "items" has not been defined

Having some trouble with an AngularJS service where I am attempting to add an item to an array every 5 seconds. However, I keep encountering the error 'items is not defined' after the first dynamic addition... I've been tinkering with this ...

Unable to access image from JSON within Mobile Angular Ui utilizing Angular Js

Currently, I am able to retrieve various data from JSON such as Price and Display Order, but I am facing difficulty in fetching the image. HTML: <div ng-controller="chooseProductDescription"> <div ng-repeat="cat in productDescrip ...