0

I'm trying to do a loop that modifies an array and after completing the whole loop the idea is to execute some code with the modified array, but when I try to do it the code after the loop is executed before the array has been modified.

I wonder if there is a way to do it, like executing the loop synchronously.

I've tried using callbacks and async/await calls, but it didn't work for me.

for (m in muns) {
  model.findAll({
    ...
  })
  .then((con) => {
    if (con.length != 0) {
      for (c of con) {
        if (!(muns.includes(c.origen))) {
          muns.push(c.origen)
        }
        if (!(muns.includes(c.destino))) {
          muns.push(c.destino)
        }
      }
    }
  });
}
console.log(muns)

I Expected to get muns array modified, but instead it hasn't change.

vsync
  • 118,978
  • 58
  • 307
  • 400
  • The `findAll` is asynchronous, so the `console.log` executes before it finishes. You need to process the result in the `then` function. – peeebeee Sep 03 '19 at 08:38
  • This is a problem due to how `Promise`s work. You can't really get values from outside your `Promise` because it is running asynchronously, so what I can suggest is that you move `console.log(muns)` just after the for-loop, or `return muns` from inside the `then` callback and use `then` again to access the data. – ionizer Sep 03 '19 at 08:38

2 Answers2

0

Since findAll is asynchronous, the code after it will execute right away, without waiting for it to be finished. To get around this, you can just move the console.log to inside the then callback:

model.findAll({ ....}).then((con) => {
    if (con.length != 0) {
        for (c of con) {
            if (!(muns.includes(c.origen))) {
                muns.push(c.origen)
            }
            if (!(muns.includes(c.destino))) {
                muns.push(c.destino)
            }
        }
    }
    console.log(muns)
});
Shahzad
  • 2,033
  • 1
  • 16
  • 23
0

This is how asynchronism works.

  model.findAll({ // This is done FIRST
    ...
  })
  .then(() => { // This is done whenever it's done, so it will happen THIRD
    ... 
  });

  console.log(muns) // This is done SECOND

One way to deal with it :

  model.findAll({ // This is done FIRST
    ...
  })
  .then(nextFunction); // This is done whenever it's done, it will happen SECOND

  const nextFunction = () => console.log(muns) // This is done THIRD 
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63