0

My JS code behaves in a strange way. I use $.tGET to get some JSON data. It works fine like this:

let UserCssLocal = "dd";
$.tGET('style',{username: text},function(r){
     UserCssLocal = r.css;
});

If I add window.alert(UserCssLocal); inside the $.tGET it works perfectly; but if I do it after the $.tGet it keep showing the "dd". How do I fix this? I feel confused!

YakovL
  • 7,557
  • 12
  • 62
  • 102
  • 2
    That `$.tGET()` function is *asynchronous*. It returns immediately, and the function you pass as the callback is called later when the operation is finished. – Pointy Sep 11 '18 at 18:03
  • @Pointy what is `$.tGET()` This my google search result https://www.google.co.in/search?q=%24.tGET()&rlz=1C1GCEA_enUS809IN809&oq=%24.tGET()+&aqs=chrome..69i57j0l5.3499j0j4&sourceid=chrome&ie=UTF-8 – brk Sep 11 '18 at 18:04
  • Try displaying the alert inside the callback function. – fsinisi90 Sep 11 '18 at 18:05
  • $.tGET = function(action,data,callback){ $.get('php/classes/userstyle.php?action='+action,data,callback,'json'); } thats my tGET so @pointy how i can solve this? – Achraf Abdmouleh Sep 11 '18 at 18:05
  • @brk I have no idea but it's clear from the description of the behavior that it must be asynchronous. – Pointy Sep 11 '18 at 18:06
  • @vlaz is not ajax bro – Achraf Abdmouleh Sep 11 '18 at 18:06
  • @AchrafAbdmouleh it is - `$.get` is a shortcut to `$.ajax({method: 'GET'})` besides - it's asynchronous - that question tackles that, not really only AJAX. – VLAZ Sep 11 '18 at 18:08
  • i try that before and didn't work thats why i tell u its not ajax, im not that good with that, just i don't know why it can't change the global value – Achraf Abdmouleh Sep 11 '18 at 18:09
  • @vlaz so how i can change to make this work? – Achraf Abdmouleh Sep 11 '18 at 18:10
  • Look at the answer - it's really thorough. There is no one way to change it in order to make it work as you expect. You have to pick one method that works for you - they are outlined in the other question. – VLAZ Sep 11 '18 at 18:12
  • @vlaz i don't know really what to use, if u can guide me will appreciate and sorry for bother – Achraf Abdmouleh Sep 11 '18 at 18:20
  • 2
    If some code depends on the variable you need to put it into the callback function too. Asynchronicity is a concept you should understand when using JavaScript. Just google it or look through the questions on stackoverflow – Josh Sep 11 '18 at 18:23

1 Answers1

0

How do I fix this? I feel confused!

You call it from inside $.tGET as you mentioned. The function is async, and program flow continues before $.tGET's function is invoked.

You can use some 'sugar' to make this seem more like you expect.

async function getIt(){
  return new Promise(resolve, reject){
  $.tGET('style',{username: text},function(r) {
     resolve(r.css)
   });
  }
}

async function doIt(){
  UserCssLocal = await getIt()
  window.alert(UserCssLocal)
}
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78