You can combine objects

0

I have the need to use vue-resource to obtain multiple JSONs that basically are the same only as there are many elements the API is limited to consume only 1000 records, but I want to collect all of them in the same object, so I made a small loop to consume the API based on the record counter that returns:

 created(){
    this.$http.get('/api/transactions?senderId=8642612272713533685S&limit=1&offset=000')
    .then( function(res){
      console.log(res.body.count);
      let limit = Math.ceil(res.body.count/1000);
      console.log(limit);
      let m = {};
      let off = 0;
        for (var i = 0; i <= limit; i++) {
          this.$http.get('/api/transactions?senderId=8642612272713533685S&limit=1000', {params:{offset: off}})
          .then( function(data){
             this.lista = { ...this.lista, ...data.body.transactions } 
          } )
          off = off + 1000;
       }
      }
    );
  }

But in the end this.list does not return the combination of all transactions, does anyone know how to solve it?

    
asked by user3215778 10.05.2018 в 21:52
source

1 answer

0

Assuming that lista and data.body.transactions are objects (it would not make sense to use the spread operator otherwise) it would be correct to declare your method created as asynchronous:

async created() {
   let result = await this.$http.get('/api/transactions?limit=1&offset=000');
   this.limit = Math.ceil(result.body.count/1000);
   let off = 0;
   for (var i = 0; i <= limit; i++) {
      result = await this.$http.get('/api/transactions?limit=1000', {params:{offset: off}});
      this.lista = { ...this.lista, ...result.body.transactions }; 
      off = off + 1000;
   }
}

As an example, since apparently the snippets do not support async I leave you something equivalent using promises:

var datos=[
{dato1: 1},
{dato2: 2},
{dat03: 3},
];

function getElemento(off) {
  return new Promise((resolve)=> {
    window.setTimeout(()=>{
       resolve(datos[off]);
       return;
    },300);
  });
}

var limit=datos.length,
    lista={};

function populateLista(off,listaparcial) {
    return getElemento(off).then((elemento)=> {
      console.log('iteración ${off}');
      listaparcial = { ...listaparcial, ...elemento};
      off++;
      if(off >= limit) {
        return listaparcial;
      }
      return populateLista(off, listaparcial);
    });
}

function created() {
  populateLista(0,{}).then((lista)=>{
    console.log(lista);
  });
}
created();
    
answered by 11.05.2018 в 14:46