Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map URL data in a Single object using Javascript?

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>
like image 396
Parkar Avatar asked Aug 14 '26 05:08

Parkar


1 Answers

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);
});
like image 159
Lennholm Avatar answered Aug 16 '26 18:08

Lennholm