Callback is blocking.. (JavaScript)

Started by
1 comment, last by y2kiah 11 years, 1 month ago

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?");

Advertisement

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

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.

This topic is closed to new replies.

Advertisement