.then(function(json1){ return json1 })
That's an unnecessary, (nearly) identity call.
.then(function(json1){ …;
You should always return
from a then
callback, so that the new promise gets a value. You can even return promises, which will be "unwrapped"!
Should I be nesting .then statements in each other?
It doesn't really matter whether you nest them or chain them, that's the great thing about promises. Chaining them reduces the height of your "pyramid", so it is considered cleaner, however you cannot access the variables from higher scopes. In your case, you need to access json1
, so you have to nest them.
I'm not completely sure how to get the both variable.
When you do return
from the callbacks, you can get it as the resolution value of the promise that you get back from the then
call.
$.getJSON('http://www.json1.com').then(function(json1){
return $.getJSON('http://www.json2.com').then(function(json2){
return {one: json1, two: json2};
})
}).then(function(both) {
// do something with both!
});