如何使用Javascript在单个对象中映射URL数据?

Sha*_*rat 2 javascript jquery ecmascript-6 vuejs2

我有一个使用vue js的单页面应用程序.现在我必须从3个不同的源URL获取数据,然后需要在对象中映射以在应用程序上使用它.

或者在将其映射到后端后从一个URL获取它是否更好?

$.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.
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

Len*_*olm 6

使用承诺:

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.
});
Run Code Online (Sandbox Code Playgroud)

写得更有效率和优雅:

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);
});
Run Code Online (Sandbox Code Playgroud)