Combining multiple ajax requests with promises

I am looking for a chain of several ajax requests, something like: get the first JSON if it succeeds and get the second JSON if it successfully makes a new object consisting of 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 embed expressions .theninto each other? I'm not quite sure how to get the variable both.

+4
source share
2 answers
.then(function(json1){
    return json1
})

This is an unnecessary (almost) identification code.

.then(function(json1){
     …;

You should always returnfrom the callback thenso that the new promise gets the value. You can even return promises to be "deployed"!

Should I be nested. then statements to each other?

, , promises. "", , . json1, .

, .

return , , then.

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

. , . , both , , both . , both , both, , , , .

, .

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

, URL- . , both , .

-3

Source: https://habr.com/ru/post/1540615/


All Articles