0

Whenever I use a forEach loop (or a for loop), the values that I assign to my variables get changed, this is the code I am using:

var myArray = [ { a: 'Val1', b: 'Information Message1' },
  { a: 'Val2', b: 'Information Message2' },
  { a: 'Val3', b: 'Information Message3' } ]
var mainArray = [];
myArray.forEach(function(info) {
    let value1 = info.a;
    let value2 = info.b;
    console.log('Pos 1: ' + value1);
    if (!allowedValues.includes(value1)) { value1 = 'Default'; }
    if (allowedValues.includes(value1)) {
        request.post(
        'https://apilink.com/api', {
            json: { varA: value1, varB: value2 }
        },
        function(error, response, body) {
            if (!error && response.statusCode == 200) {
                mainArray.push(body.value);
                console.log('Pos 2' + value1);
            } else { console.log(error); }
        }
        )
    }
});

The names will all show up at once for the first time I console.log in the for loop, but the second time I call console.log in the for loop, the array's position is different:

Pos 1: Val1
Pos 1: Val2
Pos 1: Val3
Pos 2: Val2
Pos 2: Val1
Pos 2: Val3
Mosukoshide
  • 71
  • 10
  • 2
    `request.post()` is an async operation. If you want to have it in the order it's been called, you have to promisify the `request.post()` and put it into `Promise.all()` – Sebastian Kaczmarek Jan 04 '20 at 21:44
  • Your asynchronous operations are non-blocking. That means the `forEach()` loop zips through the loop and starts all the operations. They then finish at random times in the future. If some take less time to process, they will finish first. The order of finish is not guaranteed or predictable in any way. See examples in the question yours is marked a duplicate of for ways to either run these async operations one at a time in serial order to to run then in parallel and keep track of the results in order. – jfriend00 Jan 05 '20 at 00:28
  • Also see [How to synchronize a sequence of promises](https://stackoverflow.com/questions/29880715/how-to-synchronize-a-sequence-of-promises/29906506#29906506) – jfriend00 Jan 05 '20 at 00:29

0 Answers0