0

I am trying to read in data from a file and save it into an array using jquery's get function. However, because the get function is asynchronous, the code after the $.get function call runs and the data is undefined. How can I run the code following the $.get function call only after the call is completed and data has been returned?

I have tried setting async to false, but the console log gives the error that it is deprecated.

    class CharacterDatabase{
      constructor(fName){
        this.fileText = readFile(fName);
        this.fileText = this.fileText.split(/[\r\n]+/);
      }
    }

    function readFile(fName){
      console.log(fName);
      $.get(fName, function(data){
        return data;
      }, "text");
    }

    var cd = new CharacterDatabase("text.txt");

The error:

main.js:32 Uncaught TypeError: Cannot read property 'split' of undefined at new CharacterDatabase (main.js:32) at main.js:85

is thrown in the console.

Line 32 is:

this.fileText = this.fileText.split(/[\r\n]+/); 

When setting async to false the error states that synchronous XMLHTTPRequests are deprecated.

  • The issue is that `return data` doesn't return from the `readFile` function, it only returns from the anonymous function passed to `$.get`. Meaning that `readFile` doesn't has a return value at all, thus the result will always be `undefined`. Have a look at the duplicate links for more info. – 3limin4t0r May 26 '19 at 18:43
  • https://javascript.info/async-await – Tekill May 26 '19 at 18:44

1 Answers1

0

A simple solution would be to wrap the call in a Promise and use async/await:

class CharacterDatabase{
  constructor(fName){
    this.init();
  }
}

async function init() {
    this.fileText = await readFile(fName);
    this.fileText = this.fileText.split(/[\r\n]+/);
}

async function readFile(fName){
  console.log(fName);
  await new Promise((resolve) => {$.get(fName, function(data){
    resolve(data);
  }, "text")});;
}

var cd = new CharacterDatabase("text.txt");

As a sidenote, I would generally not advise to put any I/O operations in a constructor.

fjc
  • 5,590
  • 17
  • 36