0

I've a method like this in my ts file

getInitialBatches() {
    var i = 0;
    for (var dto of this.transferDTO.stockMovesDTOs) {
        i++;

        this.queryResourceService
            .getBatchIdUsingGET(this.batchParams)
            .subscribe((data) => {
                this.allBatches[i] = data;
            });
    }
}

Since getBacthIdUsingGET is a callback, It is not functioning the way I want.loop control variable i gets increased by more than 1 by the time call back gets invoked so I'm not able to put values into every index of allBatches array, Value is getting placed into random indexes. how to solve this issue?

B45i
  • 2,368
  • 2
  • 23
  • 33
Arjun
  • 1,116
  • 3
  • 24
  • 44
  • Does this answer your question? [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – ASDFGerte May 01 '20 at 13:40

1 Answers1

1

There are some issues with vars in loops, and it was specifically part of the let specification that lets this work properly. https://wesbos.com/for-of-es6

In general, it's best practice to avoid using vars due to their weirdness in certain instances and their scoping mechanisms.

getInitialBatches() {
    for (let i = 0; i < this.transferDTO.stockMovesDOTs.length; ++i) {
        this.queryResourceService
            .getBatchIdUsingGET(this.batchParams)
            .subscribe((data) => {
                this.allBatches[i] = data;
            });
    }
}
B45i
  • 2,368
  • 2
  • 23
  • 33
Zachary Haber
  • 10,376
  • 1
  • 17
  • 31