How can I get the file contents or server response to a global variable? In the following function, the global variable after the function remains undefined , whereas if you call alert inside the function, the value is assigned to it.

I need to read a few files and send to the service API with a half dozen requests, and then digest it all. If you do the ladder, then in this ladder, I drown. I would like to get the variable out of the function. Is it possible

<script> var myVar; $.get("example.html", function(data) { myVar = data; alert(myVar); // всё отлично }, "html"); alert(myVar); // undefined </script> 

Reported as a duplicate by AK participants, Community Spirit 20 Sep '18 at 16:45 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • you can use axios , it is built on promises, there will be no “hell of callbacks” - Ilya Zelenko

3 answers 3

Yes, you can write everything in one row using asynchronous functions.

 <script> (async function(){ var myVar; myvar=await $.get("example.html", "html"); alert(myVar); })() </script> 

Interactive example:

 var fakeAjax=value=>new Promise(resolve=>setTimeout(()=>resolve(value),2000)), global (async function(){ console.log('Wait...') global=await fakeAjax('Yay! It\'s inline asynchronus response!') console.log(global) })() 

This will work with any promise objects, as well as functions that return it ( $.get one of them).

    The first time I answer here :)

    $ .get works asynchronously, that is, when you print the myVar variable, it is really empty.

    Try this:

      var myVar; $.get("example.html", function(data) { myVar = data; // alert(myVar); // всё отлично }, "html").then(function(){ alert(myVar); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

      It turns out jquery get also returns a promise, you can work with it like this:

       $.get("https://jsonplaceholder.typicode.com/todos/1").then(function (myVar) { console.log(myVar) }) 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

      How to work with promises, create a chain with them can be read here .