Home > Software engineering >  How to wait for .forEach() to complete with sequence and order
How to wait for .forEach() to complete with sequence and order

Time:08-10

How to do this foreach one after the other?

const data = [1, 2, 3, 4]

        data.forEach((i) => {
            console.log(i)
            setTimeout(() => {
                console.log("hello")
            }, 500);
        })

Output - 1, 2, 3, 4, hello, hello, hello, hello

expected output - 1, hello, 2, hello, 3, hello, 4, hello

CodePudding user response:

You can call inside setTimeout function to achieve result. But you have to wait for 500 miliseconds every time to call this:

const data = [1, 2, 3, 4]

        data.forEach((i) => {
           
            setTimeout(() => { console.log(i);
                console.log("hello")
            }, 500);
        })

Output - 1, hello, 2, hello, 3, hello, 4, hello

CodePudding user response:

const data = [1, 2, 3, 4]
        data.forEach((i) => {
            console.log(i)
            console.log("hello")
        })

You can simply do this without using setTimeout

  • Related