0

could you tell me why the value of the global variables below are lost?

  public maximo: number[];
  public minimo: number[];
  public media: number[];

they are in a typescript file.

I fill them inside the typescript method below. the first console.log prints correctly the values. the second is empty. I didn't understand why the second is empty. Could you tell me why, please?

  buscaTempos(quantidade: number) {

this.maximo = [];
this.minimo = [];
this.media = [];
this.recursos = [];

    this.tempoRespostaRecursoService.getTempoRepostaRecursos(quantidade).then((res) => {

        if(res.httpRequest!=null) {
            this.tempo = JSON.stringify(res);

            var jsonData = JSON.parse(this.tempo);

            for (var j=0; j < jsonData.httpRequest.length; j++) {
                    var counter = jsonData.httpRequest[j];
        this.maximo.push(counter.itemDTO.maximum);
        this.minimo.push(counter.itemDTO.minimum);
        this.media.push(counter.itemDTO.average);
        this.recursos.push(counter.rest);

    }
        console.log(this.maximo);
        }
});

console.log(this.maximo);
}
Marcel
  • 421
  • 2
  • 8
  • 18
  • 1
    They aren't lost, they're just not filled in yet when you log them. `then` callbacks are **always** asynchronous (typically because the underlying operation the promise represents is asynchronous, but the spec makes them *always* in order to avoid making the callbacks chaotic). So nothing is pushing anything into those arrays until *later*, after `buscaTempos` has logged the results and returned. See the linked question's answers for more info. – T.J. Crowder Mar 06 '18 at 17:23
  • could you give me some more tip of how could I solve that, please? – Marcel Mar 06 '18 at 17:25
  • Again: See the linked question's answers. – T.J. Crowder Mar 06 '18 at 17:26
  • 1
    But: You probably want to return the promise created by `then` out of `buscoTempos`, for two reasons: 1. So the caller knows when those arrays have been filled in. 2. So the caller can handle errors. Right now, if the promise returned by `this.tempoRespostaRecursoService.getTempoRepostaRecursos` rejects, nothing handles that rejection (and you'll get an "Unhandled rejection" error in the console). Remember one of the cardinal rules of promises: Either handle rejections (errors), or pass the promise out of the function so the caller can. – T.J. Crowder Mar 06 '18 at 17:27
  • i tried adding the code below but didn't solve. resolve(); } }).catch(error => { reject(); }); }); – Marcel Mar 06 '18 at 18:33
  • 1
    solved. understood your message. thanks. – Marcel Mar 06 '18 at 18:58

0 Answers0