N. Levenets
N. Levenets

Reputation: 87

Node.js: Execution after for loop

I'm building some Node.js app and have a function like this:

function ex() {
  allowUA = false;

  for (var i = 0; i < arr.length; i++) {
    (function(index) {
      setTimeout(() => {
        console.log(index);
      }, i * 3000);
    })(i);
  }

  if (i == arr.length - 1) {
    allowUA = true;
  }
}

All I want is that function to execute in strict order (changing variable to false, doing the loop and then changing variable back to true)

I found out that it's not as easy as it seems, so I ask for your help.

Is there a way to do this? Thanks in advance.

Upvotes: 1

Views: 1854

Answers (2)

Andy
Andy

Reputation: 63550

Here's an async/await method that that forgoes a for/loop in favour of a setTimeout that calls a function with an slowly-shortening array:

async function ex(arr) {
  allowUA = false;
  console.log(allowUA);

  function logger(arr) {
    return new Promise((resolve, reject) => {
      (function loop(arr) {
        const [head, ...rest] = arr;
        if (!arr.length) {
          resolve();
        } else {
          console.log(head);
          setTimeout(() => loop(rest), head * 1000);
        }
      }(arr));
    });
  };
  
  await logger(arr);

  allowUA = true;
  console.log(allowUA);
}

const arr = [1, 2, 3, 4];
ex(arr);

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

You can use Promise to make sure that the timeout resolves first and then log the next condition when all the promises resolve.

let allowUA = false;
let arr = [1, 2, 3]

function ex() {
  allowUA = false;
  console.log('false');

  // iterate over the array and create a promise for each iteration
  let promises = arr.map(function(value, index) {
    return new Promise(function(resolve) {
      setTimeout(() => {
        console.log(index);
        // resolve the promise
        resolve();
      }, index * 500);
    });
  })

  // run this when all the promises resolve themselves
  Promise.all(promises).then(function() {
    allowUA = true;
    console.log('true');
  });
}

ex()

Upvotes: 1

Related Questions