I have a single page application using vue js. Now I have to get data from 3 different source URL and then need to map in an object to use it on the application.
Or is it better to get it from ONE URL after mapping it on the backend?
$.get(furl, function(data) {
this.items1 = data;
});
$.get(furl, function(data) {
this.items2 = data;
});
$.get(furl, function(data) {
this.items3 = data;
});
// if I want to merge it here. I am not getting items1, items2, items3 here.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Use Promises:
Promise.all([
new Promise(function(resolve) {
$.get( furl, function( data ) {
resolve(data);
});
}),
new Promise(function(resolve) {
$.get( furl, function( data ) {
resolve(data);
});
}),
new Promise(function(resolve) {
$.get( furl, function( data ) {
resolve(data);
});
})
]).then(function(results) {
// The items will be available here as results[0], results[1], results[2], etc.
});
Written more efficiently and elegantly:
function promisifiedGet(url) {
return new Promise(function(resolve) {
$.get(url, resolve);
});
}
Promise.all([
promisifiedGet(furl1),
promisifiedGet(furl2),
promisifiedGet(furl3)
]).then(function(results) {
console.log(results);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With