Skip to content
Advertisement

Loading text from a file in JavaScript

I have created a function to get text from a file using an url. The function uses $.get() of jQuery to fetch the file. The function works fine but the problem here is $.get() is asynchronous so the order of the output is not predictable i tried changing it to synchronous but it freezes the page completely i have tried waiting for it to respond thinking i would take time but it didn’t work.

Here’s my code.

var File = (function () {
  return {
    GetTextFromFile:function(filePath) {
      console.log ("Start")

      $.get({
        url:filePath,
        async:true
      }, function (data) {
        console.log(data)
      });
      
      console.log ("End")
    }
  }
})();

This function outputs

Start
End
'Content_of_the_file'

This creates of problem because i cannot return the content of the file since it’s not loaded yet because of the asynchronous get function. So is there any way to tell the function to wait till the $.get() has returned the content of the file.

Advertisement

Answer

Using async await we can make asynchronous to work in sync mode.

var File = (function () {
  return {
    GetTextFromFile: async function(filePath) {
      console.log ("Start")

      data = await $.get({
        url:filePath,
        async:true
      }, function (data) {
        return data
      });

      console.log(data)

      console.log ("End")
      return data
      
      
    }
  }
})();

await File.GetTextFromFile()
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement