1
$(document).ready(function () {
    $.get("...", function (domus, status) {
        console.log(1);
    }
    console.log(2);
}

Using this code, according to JavaScript asynchronous rules, console.log(2) is executed (and printed) before that console.log(1).

I need to execute the callback returned by $.get (what's printing console.log(1)) strictly before the following code lines.

x80486
  • 6,627
  • 5
  • 52
  • 111

3 Answers3

0

In short, you can't.

There is no way to force asynchronous functions to be synchronous. Instead, if you have something asynchronous, you have to build all of your code to handle that.

Your best bet is just to embrace the asynchronicity and build it in to handle it:

$.get('', function () {
  console.log(1);
}).then(function () {
  console.log(2);
});

In the long run, that'll cause you the fewest headaches.

There are other ways to deal with it, like using values to track if certain things are done and then set timeouts to check periodically:

let ready = false;

$.get('', function () {
  ready = true;
  console.log(1);
});

function checkReady() {
    if (ready) {
      console.log(2);
    } else {
      setTimeout(checkReady, 500);
    }
}

checkReady();

This will check every 500ms if it's ready before running. This will let you kind of hide the async nature of your code. This can work in scenarios where you have very, very few async operations, but it can also cause confusion and weird bugs if you aren't careful, so use it carefully.

samanime
  • 25,408
  • 15
  • 90
  • 139
0

You cannot completely avoid async behaviour in Javascript, but can handle it in different way.

One Way to handle this is, call it afterwards using another fucntion

$(document).ready(function(){
     $.get("...", function(domus, status){

        console.log(1);
        printLog2();
     }     
    } 

     function printLog2(){
      console.log(2);
     }
Prabodh M
  • 2,132
  • 2
  • 17
  • 23
-1

You can do it using jquery deferred approach. Refer it from here, if you do not know much about deferred

var deferred = $.Deferred();

$.get("https://baconipsum.com/api/?type=meat-and-filler", function (domus, status) {
        deferred.resolve();
});

deferred.done(function() {
   console.log(1);
}).
then(function() {
   console.log(2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Nilesh Khisadiya
  • 1,560
  • 2
  • 15
  • 27
  • 5
    While your code may work, a little description of why it's relevant to the problem would really help to educate the OP and any future visitors – Rory McCrossan Jun 21 '17 at 14:42
  • @RoryMcCrossan : May be you understand above solution as I posted before. I hopes it will help to educate to future visitors :-) – Nilesh Khisadiya Jun 22 '17 at 09:57