嵌套的getJSON调用

时间:2016-10-10 23:53:58

标签: javascript jquery json nested getjson

所以..我是这个Javascript的新手并使用JSON。我正在开发一个网页,在这种情况下需要评论,然后是当前的用户名。

为了开发它,我尝试创建一个使用getJSON()方法返回用户名的函数,但显然这不起作用。我想出的是使用嵌套的getJSON调用。

这样的事情:

$.getJSON(getCommentsURL, function(jsonComments){
    $.getJSON(getUsernameURL, function(username){
        jsonComments[0].deleteButton = (jsonComments[0].username === username)
        // programming logic
    });
});

主要是,代码示例的第3行中描述了我需要这两种信息的原因。

我的问题是,这种实现是否可以接受?它确实有效,但可能有更合适的方法来实现此实现。我关心约定的原因,以及做到这一点的适当方法,不仅仅是为了我自己的知识,而是因为它是一个学校作业,要求代码干净整洁(不仅仅是它有效)。

非常感谢任何答案。

2 个答案:

答案 0 :(得分:2)

这是使用jQuery对Promise.all - $.when的回答的一个很好的用例。

var commentsPromise = $.getJSON(getCommentsURL);
var usernamePromise = $.getJSON(getUsernameURL);

// when both requests complete
$.when(commentsPromise, usernamePromise).then(function(jsonComments, username) {
  jsonComments[0].deleteButton = (jsonComments[0].username === username)
  // programming logic
});

答案 1 :(得分:1)

问题的方法应返回预期结果,您也可以使用.then()。您还可以将.fail().catch()链接到.then()来处理错误。请注意return

中的.then()声明
$.getJSON(getCommentsURL)
.then(function(jsonComments) {
    return $.getJSON(getUsernameURL)
           .then(function(username){
             jsonComments[0]
             .deleteButton = (jsonComments[0].username === username)
             // programming logic
           });
})
.fail(function(jqxhr, textStatus, errorThrown) {
  console.log(errorThrown)
})
相关问题