Jump to content

View more

Image of the Day

I've done more tweaks to my color palette selector. #gamedev #screenshotsaturday #madewithunity https://t.co/aJXrC4ruRg
IOTD | Top Screenshots

The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.


Sign up now

Callback is blocking.. (JavaScript)

4: Adsense

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.


  • You cannot reply to this topic
2 replies to this topic

#1 Schoening   Members   

141
Like
0Likes
Like

Posted 05 March 2013 - 11:50 PM

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

 

 



#2 Schoening   Members   

141
Like
0Likes
Like

Posted 05 March 2013 - 11:54 PM

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



#3 y2kiah   Members   

1990
Like
1Likes
Like

Posted 06 March 2013 - 12:29 AM

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.




Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.