0

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?

2
  • 2
    You can't do that. You have to work with the Javascript event loop, there aren't any threads (at least not that are accessible to you, the programmer) to tie up. You can create a boolean flag, schedule a callback that checks it before executing, and have that callback also enqueue another to run it every tick of the event loop until the flag changes to avoid blocking. You can also spawn subprocesses, although communicating with them is significantly harder than shared memory threads. Commented Jan 31, 2021 at 18:02
  • The general design principle in Javascript is to create or find an event that you can use to monitor and then carry out some action. You don't "poll" or "spin" or "loop" constantly checking something as that hogs the single thread that your Javascript is run in (and is horrible for CPU utilization and battery life anyway). Javascript implementations in the browser and in nodejs are event driven at their core and need to be programmed that way. Commented Jan 31, 2021 at 18:44

1 Answer 1

2

I think I misunderstood what async functions actually are.

I am not a back end guy, but will give it a shot. Nodejs still runs in a single thread. So an infinite loop will block the whole program. Asynchronous doesn't mean that the provided callback runs in a separate thread. If nodejs was multithreaded you could have infinite loop in one thread, that wouldn't block the other one for example.

Asynchronous means that the provided callback won't be run immediately, rather delayed, but when it is run it is still within that one thread.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.