异步获取请求返回true

Async Get Request return true

本文关键字:true 返回 请求 获取 异步      更新时间:2023-09-26

我有代码:

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" );

目前我的输出是:B, C

我很困惑为什么代码不进入A作为true被返回。这和asynchronous request有关系吗?

是的,这是因为ajax是异步的。当你调用venue_exists时,它返回undefined。
如果你需要检查,你需要同步调用它。

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