Executing another function after reader.Onload() in vue js

Viewed 143

I need to read a text file and pass data as object to another function in vue2. The uploadBulk function reads the text file and submitBulk() will be executed only after finished reading the file. But now submitBulk() is being executed before and while i printing obj inside submitBulk its returning an error that the obj is undefiend or null. I have the following code-

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()


        }
        };
      }

    }
1 Answers

Dose this async/await code help?

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)
  })
  */
}
Related