Performing a subsequent action following the completion of reader.Onload() in a Vue.js application

I am facing an issue where the submitBulk() function is being executed before the uploadBulk function finishes reading a text file and passing data as an object to another function in vue2. When I print obj inside submitBulk, it returns an error stating that obj is undefined or null. Below is the code I am using:

uploadBulk: function (){
      if (this.qCategory == 'MCQ') {
      var questions = []
      var file = this.$refs.uploadedFile.files[0];
      if (file) {
        var reader = new FileReader();
        reader.readAsText(file, "UTF-8");

        reader.onload = () => {
          /// mcq

          var str = reader.result;
          const obj = str.split(/\n/u).reduce((acc, line, i) => {
            if (i%2===0) acc.questions.push({"body":line.match(/\(.+\)(.*)/u)[1].trim()});  // remove the (X) from the question
            else {
              const curItem = acc.questions[acc.questions.length - 1]; // last pushed object
              let [optionStr, answer] = line.split(/। /u);// split on this special character
              // assuming 4 options
              curItem.options = optionStr
                  .match(/\(.+\) (.+) \(.+\) (.+) \(.+\) (.+) \(.+\) (.+)/u)
                  .slice(1); // drop the first element from the result (full match)
              answer = answer.match(/\((.+)\)/u)[1]; // just get the letter from the bracket
              curItem.answers = [answer];
              curItem.type = "MCQ"

            }
            return acc
          }, {questions: []})
          this.submitBulk()
        }
        };
      }

    }

Answer №1

Can this async/await function be of assistance?

uploadBulk: async function () {
  const file = this.$refs.uploadedFile.files[0]
  if (!file || this.qCategory !== 'MCQ') return
  
  /// MCQ
  const questions = []
  const str = await file.text() // wait for text to be read
  const lines = str.split(/\n/u)

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]
    if (i % 2 === 0) {
      questions.push({ 
        // remove the (X) from the question
        body: line.match(/\(.+\)(.*)/u)[1].trim()
      })
    } else {
      const curItem = questions[questions.length - 1] // last pushed object
      let [optionStr, answer] = line.split(/। /u) // split on this special character
      
      // assuming 4 options
      curItem.options = optionStr
        .match(/\(.+\) (.+) \(.+\) (.+) \(.+\) (.+) \(.+\) (.+)/u)
        .slice(1) // drop the first element from the result (full match)

      curItem.answers = [
        answer.match(/\((.+)\)/u)[1] // just get the letter from the bracket
      ]
      curItem.type = 'MCQ'
    }
  }

  this.submitBulk()

  /**
  // TODO: Do something with `questions` or `obj`
  const obj = { questions }
  return obj

  // TODO: Then get the result with 
  uploadBulk.then(obj => {
    console.log(obj)
  })
  */
}

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

How can I add divs to an HTML page with a Javascript animated background?

I am currently facing an issue with my JavaScript animated background, consisting of just 3 pictures. I am trying to display some Div elements on it with content inside. Here is the code snippet I have right now: In my CSS file, I have defined styles for ...

What is the process for retrieving data from a website?

Currently, I am in the process of setting up an automated test using the basic page object pattern. The objective is to open Google, input a search query, click on a link from the results, and retrieve the information. So far, I have successfully navigated ...

Checking the formik field with an array of objects through Yup for validation

Here is a snippet of the code I'm working on: https://codesandbox.io/s/busy-bose-4qhoh?file=/src/App.tsx I am currently in the process of creating a form that will accept an array of objects called Criterion, which are of a specific type: export inte ...

Having trouble with JavaScript not working when clicking an image and toggling a div?

Why isn't the onclick image and toggle div functionality working with JavaScript? I made the change from: <input type="button" id="Showdiv1" name="Showdiv1" value="Show Div 1" onclick="showDiv('div1')" /> to: <img src="https://d ...

Having issues with the Carousel feature in Bootstrap 5.3.1 while using Angular version 15

I'm currently in the process of setting up a carousel on my homepage. It seems like everything is in place, but there's something missing. The initial image, text, and arrows all display properly, but they are non-functional. I have correctly imp ...

Having trouble locating the index page in my Nuxt2 project

I am struggling to solve a particular issue with my website. I cannot locate my index page in the pages folder - what could be causing this problem? index.vue <template> <h1> Hello world </h1> </template> Even when I created a ...

Retrieving JavaScript array data following a page reload

I am facing an issue with updating an array dynamically in my C# server-side code and then utilizing the updated data in a JQuery function on my webpage. When the page first loads, the array is filled with some default values by C#. However, when a user ma ...

Embed HTML code into a React/Next.js website

I've been given the task of enhancing the UI/UX for an external service built on React (Next.js). The company has informed me that they only allow customization through a JavaScript text editor and injecting changes there. However, I'm having tro ...

Converting jQuery selectors into JSON objects

I would like to create a JSON object from a jQuery selector string, which is the text inside $(), without actually selecting elements from the DOM. Is there a built-in function in jQuery that can achieve this task or are there any open-source libraries ava ...

Is it possible to modify the colors within a JavaScript string?

I am currently working on creating a multi-timezone clock that will be shown in a web browser in kiosk mode. The basic code was taken from and the kiosk setup from: and then customized into: However, I am struggling to change the color of each timezon ...

React - updates to server values do not display in DOM right away

When I work from the client side, I have a modal in my HomeComponent that allows me to select an element. My goal is to then display that selected element within the same HomeComponent (in the productosEnVenta function). The element chosen in the modal is ...

Having trouble getting the form to submit with jQuery's submitHandler

I am in the process of converting a contact form to AJAX so that I can utilize the success function. Currently, I am encountering an issue where the code is halting at the submitHandler section due to it being undefined. Can anyone identify why my submitHa ...

"Initially, the input state does not establish a binding for onChange event upon

A state named account_type has been declared, and an onChange event has been created to change the state's value when the div is clicked. <div className="price-plan" value="star" onClick={() => this.setPlan("star") ...

Having trouble troubleshooting this issue where the object data is displaying in the console, but encountering an error when trying to use the resetValue

Index.html I am facing an issue while reading data from an object and the seek bar is giving a null error. The images and songs are stored locally, and I am trying to access them. <div class="music-player"> <div class="song&qu ...

Make sure to properly check the size of the image before uploading it in express js

Below is the code I have written to verify if an image's size and width meet the specified criteria: im.identify(req.files.image,function (err,features) { //console.log(features); if(features.width<1000 ...

Passing Data from Next.js Middleware to getServerSideProps during the Initial Request with the Help of Cookies

Encountering a challenge within a Next.js application (for a coding challenge). Requested flow to achieve: Check for geolocation cookie in Next middleware. If not present, fetch data and store in cookie. In getServerSideProps, utilize the cookie (if avai ...

Serialization of HTML form containing embedded objects

There is a form on my website that includes fields for address and dimensions. Here is an example of the form structure: <form id="my-form"> <fieldset name="address"> <input name="streetAddress" type="text" placeholder="Street Addres ...

Error: guild is not defined | discord.js

Having trouble with a ReferenceError that says guild is not defined? I recently encountered a similar issue with members but managed to fix it by adding a constant. As someone new to javascript and node.js, I could use some assistance. I've even tried ...

Checking to see if an object is null using Javascript/AngularJS

Below is the code snippet: function getBestBlock(size){ var bestBlock = {}; var blockEnteredTest = true; for(var i = 0; i < $scope.blocks.length; i++) { if($scope.blocks[i].state == "Free") { i ...

Upon refreshing the datatable, I encountered a issue where the checkbox cannot be selected

After updating my data table with new content through an AJAX request, I am facing an issue where I am unable to select the check-boxes in the table. I use a class selector to choose the rows that contain multiple check-boxes. The select event is placed in ...