-3

Below written javascript code runs asynchronously and produces output in the following format.

const check = () => {
    const arr = [3,2,1]

    arr.forEach(async (val) => {
        await setTimeout(() => console.log(val), val*1000)
    })
}

check();

The actual output is:

1
2
3

But I want output in the following format:

3
2
1
Prateek Oraon
  • 101
  • 1
  • 8
  • 1
    `setTimeout` doesn't return a promise so awaiting it doesn't work. Even if it did, `forEach` doesn't work for async functions. [See also](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Mark Jun 24 '19 at 14:20
  • 1
    Use an actual for loop instead of `forEach` – zero298 Jun 24 '19 at 14:20
  • Do you want it to fully wait for one to finish printing before starting the timer on the next? – Charlie Fish Jun 24 '19 at 14:20
  • Do you really want to run `setTimeout()` or some other asynchronous function? The answer will be very different depending on weather the function you want to call return a promise or does not return a promise (like setTimeout) – slebetman Jun 24 '19 at 14:22

1 Answers1

0

Recusrion might do the trick.

const check = () => {
    const arr = [3,2,1]

    var i = 0, val;
    const do_the_thing = ()=>{
      setTimeout(()=>{
        val = arr[i];
        i++;
        console.log(val);
        if(arr[i]) do_the_thing();
      }, val*1000)
    };

    do_the_thing();
}

check();
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116