Pergunta

I'm looking to chain multiple ajax requests, something along the lines of: get first JSON, if successful move on and get second JSON, if successful make a new object consisting of both JSON data.

// get first json
$.getJSON('http://www.json1.com').then(function(json1){
    return json1
}).then(function(json1){
    // get second json
    $.getJSON('http://www.json2.com').then(function(json2){
        var both = {}
        both.one = json1
        both.two = json2
        return both
    })
})

Should I be nesting .then statements in each other? I'm not completely sure how to get the both variable.

Foi útil?

Solução

.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!
});

Outras dicas

I am editing this. I misstated what the problem is. The problem is that both is defined inside of a function and it is not accessible outside of the function unless you define both as an Object outside of the function. As you have it created, both is invisible to the entire world, and the only access to both as you have it created is handle it with another deferred callback, but still you don't have a variable defined to hold that Object and more to the point doing it that way would be retarded.

Here is a clean and simple way to accomplish what you want.

 var json1=$.getJSON('http://www.json1.com');
 var json2=$.getJSON('http://www.json2.com');
 var both={};

 json1.then(json2).then(function(){
   both.one=json1.responseJSON;
   both.two=json2.responseJSON;
});

If you want to be cooler, wrap it in a function and pass the url as an argument. Just make sure to declare the both object in a scope where you can access it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top