diaco diaco - 9 months ago 92
JSON Question

nested getJSON calls

So.. I am new to this Javascript and using JSON. I am developing a webpage which in this case needs comments, then the current username.

In order to develop this, I tried to create a function that returns the username using the getJSON() method, but obviously that would not work. What I came up with instead was using nested getJSON calls.

Something like this:

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

Mainly, the reason why I need both information is described in Row 3 of the code sample.

The question I have is, is this implementation acceptable conventionally? It does work, but there might be a more appropriate way to do this implementation. The reason I care about conventions, and appropriate ways to do this, is not only for my own knowledge, but because it is a school assignment that requires the code to be clean and correct (not only that it works).

Very grateful for any answers.


This is a good use case for using jQuery's answer to 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