Jquery函数不等待Javascript函数的结果为什么?

Jquery function doesn't wait result of Javascript function result why?

本文关键字:函数 结果 为什么 Javascript 等待 Jquery      更新时间:2023-09-26

我有两个方法。第二个呼叫第一个。当我将一个警报函数放入第一个函数中时,我可以看到返回值。但是第二个函数认为值是未定义的。我不明白为什么。一个人不能处理这个值?

function getTweetReply(id_str) {
    $.getJSON("get_tweet_reply.php", {id_str: id_str}, function(json) {
      tweet_relpy = '<blockquote>'+json.results[0].text+'</blockquote>';
      alert(tweet_relpy); // --> I can see the result
      return tweet_relpy;
    });
}
$(document).on("click", ".tweet",function(){
    var id_str = $(this).attr("id");
    $.getJSON("get_tweet_details.php", {id_str: id_str},     function(json) {
        tweet = '<img src="'+json.results[0].profile_image_url+'"><br>'
                ' + json.results[0].from_user + '<br>'
                ' + json.results[0].from_user_name + '<br>'
                ' + getTweetReply(json.results[0].id_str) + '</b><br>'; // --> undefined
       $("#float").html('<div id="replybox">'+ tweet +'</div>');
    });
});

首先,将AJAX与内容生成分离,并公开承诺:

function getTweetDetails(id_str) {
    return $.getJSON("get_tweet_details.php", {id_str: id_str});
}
function getTweetReply(id_str) {
    return $.getJSON("get_tweet_reply.php", {id_str: id_str});
}
function render(details, reply) {
    // render HTML based on "details" and "reply" JSON structures
    var tweet = '...';
    $("#float").html('<div id="replybox">'+ tweet +'</div>');
}

这是关注点的分离——两个AJAX相关的函数现在不需要回调参数,返回的"承诺"允许任何数量的回调依赖于结果,也允许$.getJSON()不直接支持的错误回调工作。

那么,由于第二个查询依赖于第一个查询:

$(document).on("click", ".tweet", function() {
    var id_str = this.id; // not $(this).attr('id') !!
    getTweetDetails(id_str).done(function(details) {
        getTweetReply(details.results[0].id_str).done(function(reply) {
            render(details, reply);
        });
    });
});