For do not wait to finish requisition, it continues counting

Asked

Viewed 154 times

2

I am developing an application in Ionic and I have a problem when I do a loop loop. In this loop there is a call from a method of a previous, that makes a request put. My problem is that the for does not wait for the server to return and continue the execution, as I can synchronize the for with the request?

My code below:

getAtualizados(){

let atualizados: Cadastrolist[]=[];

this.contribuinteProvider.getAtualizados()
.then((result)=>{
  atualizados = result;
  for (var i = 0; i < atualizados.length; i++){
    this.servidorProvider.update(atualizados[i].dados.cadastro)
    .then((result)=>{
      this.contribuinteProvider.remove(atualizados[i].key);
    });
  }

});}
  • Can’t use the second result?

  • It is because the second result is the server response. It returns a code, for example: If it worked it returns 200 if not 404, only if it is not wait for that answer it continues until the Arry is finished.

1 answer

2


I managed to solve, for that I used Async/await.

async update(cadastro, id){
await this.servidorProvider.update(cadastro)
.then((result)=>{
  this.contribuinteProvider.remove(id);
});
}
async getAtualizados(){
let atualizados: Cadastrolist[]=[];

await this.contribuinteProvider.getAtualizados()
.then((result)=>{
  atualizados = result;
});

for (var i = 0; i < atualizados.length; i++){
 await this.update(atualizados[i].dados.cadastro, atualizados[i].key);
}

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.