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.

JavaScript

This function outputs

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement