0

I have the code:

if (venue_exists(instagramUserID)){
    alert('A');
}else {                              
    alert('C');
}  


function venue_exists(instagramUserID) {    
    $.get( "/venues/" + instagramUserID, function(json) {
        if (json.data.success){
            alert('B');            
            return true;
        }         
 }, "json" );

Currently my output is: B, C

I'm confused as to why the code is not going into A as true is being returned. Does this have something to do with the asynchronous request?

Any help would be greatly appreciated.

  • 3
    because $.get is **asynchronous** - the return value of venue_exists is `undefined` ... which is `falsey` - and I'm surprised your alerts don't come C then B ... NOTE: never use alert for debugging code, especially asynchronous code, it screws up what you think is happening – Jaromanda X Sep 29 '15 at 12:35

1 Answers1

0

Yes, it happens because ajax is asynchronous. When you call venue_exists it returns undefined.
If you need to have that check you need to call it synchronously.

function venue_exists(instagramUserID) {
   return JSON.parse($.ajax({
     url: '/venues/' + instagramUserID,
     type: "GET",
     dataType: "json",
     async: false
}).responseText);}
Lokki
  • 372
  • 1
  • 6
  • 20