将 AJAX GET 响应(在 JSON 中)的一部分存储到字符串变量中的问题

Issues in storing a portion of an AJAX GET response (in JSON) into a string variable

我在尝试通过 AJAX 将 GET 请求的部分结果存储到字符串变量时遇到问题。

基本上,我想让包含 GET 请求操作的特定函数 return 该操作的结果。

var count = 0;

$.getJSON("https://api.icndb.com/jokes/count", function(data){ 
    count = data.value+1;
    for (i = 1; i < count; i++){ 
        if (i != 1) {
            setTimeout(jokeGet, i*7500, i);
        }
        else {
            jokeGet(i);
        }
    }
});

function jokeGet(n) {
    var str = "";
    $.getJSON("https://api.icndb.com/jokes/" + n, function(data){
        if (data.type != "NoSuchQuoteException") {
            $(".joke").html(data.value.joke);
            str = data.value.joke;
        }
        else {
            count++;
        }
    });

    return str;
}

API 我正在请求将信息存储在 JSON 树中。以下是此类树的两个示例:

{ "type": "success", "value": { "id": 1, "joke": "Chuck Norris uses ribbed condoms inside out, so he gets the pleasure.", "categories": ["explicit"] } }

{ "type": "NoSuchQuoteException", "value": "No quote with id=8." }

但是,每当我 运行 单元测试(通过 QUnit)时,结果表明,在任何情况下,jokeGet() 函数 return 都是一个空字符串。我觉得这很奇怪,因为我认为 str = data.value.joke 行会成功,所以笑话存储在该变量 str.

显然,因为 str 总是 returns 作为空字符串,所以情况并非如此。关于为什么会这样有什么建议吗?

更新

考虑到我现在正在做的事情的目标不是让程序运行而是进行单元测试以证明程序运行,我决定包含 "unit tests" 文件:

QUnit.test("cn_jokes", function(assert) {
    function joke(n, expected) {
        assert.equal(jokeGet(n), expected);
    }
    joke(1, "Chuck Norris uses ribbed condoms inside out, so he gets the pleasure.");
    joke(8, undefined);
    joke(163, "Ninjas want to grow up to be just like Chuck Norris. But usually they grow up just to be killed by Chuck Norris.");
    joke(221, "Chuck Norris is the only person to ever win a staring contest against Ray Charles and Stevie Wonder.");
    joke(352, "Chuck Norris doesn't see dead people. He makes people dead.");
    joke(502, "Chuck Norris insists on strongly-typed programming languages.");
    joke(526, "No one has ever pair-programmed with Chuck Norris and lived to tell about it.");
    joke(598, "Once Chuck Norris and Superman had a competition. The loser had to wear his underwear over his pants.");
});

如您所见,我想获取 jokeGet() 函数,具体来说,就是 return 笑话值。请让我知道这是否可行。

尝试在 if 块中使用 return 语句

if(condition){
return str;
} else {
return
}

我想这种行为是由于 js 的异步性质造成的,它 returns 在 get 请求完成之前的值

$.getJSON是异步的;在发出请求时,您的代码将继续 运行。因此,您传递给 getJSON 运行s 的回调很早就返回了 str。你应该 jokeGet 接受一个回调函数,并在请求完成时调用它(将 data.value.joke 作为参数传递):

function jokeGet(n, callback) {
    $.getJSON("https://api.icndb.com/jokes/" + n, function(data){
        if (data.type != "NoSuchQuoteException") {
            $(".joke").html(data.value.joke);
            if (callback !== undefined && callback !== null)
                callback(data.value.joke);
        }
        else {
            count++;
            if (callback !== undefined && callback !== null)
                callback(undefined); // not sure if you want undefined or "" in this case
        }
    });
}

编辑:您可以对 QUnit 使用异步回调。只需使用 assert.async(),如前所述 here:

QUnit.test("cn_jokes", function(assert) {
    var done = assert.async();
    var jokesDone = 0;
    var numJokes = 8; // make sure to change this if you add more
    function joke(n, expected) {
        jokeGet(n, function(j) {
            assert.equal(j, expected);
            if (++jokesDone == numJokes) done();
        }
    }
    joke(1, "Chuck Norris uses ribbed condoms inside out, so he gets the pleasure.");
    joke(8, undefined);
    joke(163, "Ninjas want to grow up to be just like Chuck Norris. But usually they grow up just to be killed by Chuck Norris.");
    joke(221, "Chuck Norris is the only person to ever win a staring contest against Ray Charles and Stevie Wonder.");
    joke(352, "Chuck Norris doesn't see dead people. He makes people dead.");
    joke(502, "Chuck Norris insists on strongly-typed programming languages.");
    joke(526, "No one has ever pair-programmed with Chuck Norris and lived to tell about it.");
    joke(598, "Once Chuck Norris and Superman had a competition. The loser had to wear his underwear over his pants.");
});