• Advertisement
Sign in to follow this  

Callback is blocking.. (JavaScript)

This topic is 1785 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to understand callbacks properly so that I can iterate arrays without blocking the Server.

 

Please tell me why it is blocking.. what am I doing wrong? I would much rather run this loop, and then do something when it is finished, but not block the rest of the server.

 

Here is the code:

 

//callback test

var myID = 666;
var grid = [
    [0,0,0],
    [0,0,0],
    [0,0,0]
];


function find_empty_slot(id,callback){
    console.log("Your ID is" + id);
    callback();       
}

find_empty_slot(myID,function(){
    for(var y = 0, len = grid.length; y < len; y++){
        for(var x = 0; x < grid[y].length; x++){
            if(grid[y][x] === 0){
                console.log("I am a Callback");
            }
        }
    }
});

console.log("This should fire before the Callback?");

 

 

Share this post


Link to post
Share on other sites
Advertisement

console.log("This should fire before the Callback?"); should fire before the callback.. but it doesnt..

Share this post


Link to post
Share on other sites
It's blocking because you're telling it to block by running a tight loop, and it's behaving exactly the way you wrote it. You might be under the impression that node.js is somehow intrinsically asynchronous. It is not. Node is just V8 javascript with a runtime environment wrapped around it. The runtime environment happens to include an event loop. You have to participate in, and work with the event loop if you want to achieve the illusion of asynchronous behavior. I say "illusion" because the code you write is always going to block, unless you're making an asynchronous IO call to the OS for files or sockets or something. It's up to you to yield your long running processes back to the main event loop.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement