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?

1

1 Answer 1

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;
            });
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.