NodeJS: async function with while(true) halts the script

I have a:

  • socketio server
  • array of values
  • async function which iterates the array and deletes them

Here is the code

// import
const SocketIo = require('socket.io')

// setup
const Server = new SocketIo.Server()
const arrayOfValues = ['some', 'values', 'here']

// server welcome message
Server.on('connection', async Socket=>{

    iterateValues()  // server no longer responds, even if function is async

    Socket.emit('welcome', 'hi')
})

// the async function
async function iterateValues(){
    while(true){
        if( arrayOfValues[0] ) arrayOfValues.splice(0, 1)
    }
}

Whenever the client connects to my server, "iterateValues()" must be invoked and asynchronously remove the items from array. The problem is when "iterateValues()" is invoked anywhere, it halts the script, and the server no longer responds.

I think I misunderstood what async functions actually are. How can I create a function that can run an infinite while loop without halting the thread of other methods?

Leave a Comment