0

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.

3
  • Well you could have a stack to push whenever a new data is fetched thus order will be there with asynchronous Commented Mar 31, 2021 at 12:06
  • 2
    Does this answer your question? How do I return the response from an asynchronous call? Commented Mar 31, 2021 at 12:07
  • The async and await method worked for my problem Commented Apr 16, 2021 at 18:43

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.