0
let a = []
    for (let i=0;i<4;i++){
        setTimeout(()=>{
            a.push(i);
        },2000)
    }


console.log(a);

Here I am getting a always blank []. Please suggest a way to stop executing console.log(a) line until a gets filled.

Rohit
  • 9
  • 2
  • The code example is trying to mix asynchronous and synchronous coding techniques, which _does not work_. Using the search box to search for "aynchronous for loop" returns 907 questions, some with multiple answers. Refining the search with details of your actual use case may help reduce the number of hits. – traktor Aug 03 '22 at 10:16
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Aug 03 '22 at 10:49

1 Answers1

1

You should await setTimeout:

let a = [];
async function test() {
  for (let i = 0; i < 4; i++) {
    await new Promise((resolve) =>
      setTimeout(() => {
        a.push(i);
        resolve();
      }, 2000)
    );
  }
}

await test();

console.log(a);

Note: You can also use Promise.allSettled to run them at the same time