Call multiple apyri and call simultaneously
I have three API urls, each with the same object names, I want to call all apis at the same time.
My js:
$(document).ready(function() {
var first = 'https:first';
var second = 'https://second';
var third = 'https://third';
$('#get-data').click(function() {
var showData = $('#show-data');
$.getJSON(first,second,third function(data) {
showData.empty();
var items = data.map(function(elem) {
return $("<li />", {
text: elem.title
});
});
var list = $('<ul />').append(items);
showData.append(list);
});
});
});
+3
source to share
1 answer
API calls are asynchronous, and they are executed in the sequence that you write in your code. the execution doesn't really matter, because "then" could be called in a different order as it is executed.
If you want to do anything while executing all three services, I would recommend using async.js , take a look at the following example:
links = ['http://first','http://second','http://third']
data = [];
$('#get-data').click(function() {
// ...
async.each(links, function(link,callback){
$.getJSON(link, function(res){
data.push(res);
callback();
})
}, function(err){
if(!err){
// your code goes here
// data[0] contains data from link 1
// data[1] contains data from link 1
// data[2] contains data from link 2
}
})
// ...
});
0
source to share