Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling state in asynchronous Node classes

I'm relatively new to Node and one thing that's concerning me is how I design classes that have to maintain state when I can't be sure they won't be called again before they've finished processing the first call.

e.g.

var thing = new Thing();

// Doesn't maintain a state, call it as much as you like
thing.doSomething(function() { alert('done') });
thing.doSomething(function() { alert('done') });
thing.doSomething(function() { alert('done') });

// Maintains some sort of internal state
thing.doSomethingStateful(function() { alert('done') });

// Calling it again messes up the first call if the callback
// hasn't been hit yet because it's still waiting on an I/O 
// operation to complete. 
thing.doSomethingStateful(function() { alert('done') });

Is there a design pattern that helps solve this issue? Should I always strive to make Node classes stateless and use an internal state object to track the state of each call? Or is there a convention to differentiate classes that can be used in an asynchronous way and those that maintain a state?

like image 858
Dan Avatar asked Mar 14 '26 13:03

Dan


1 Answers

I think you are misunderstanding the node.js asynchronous model.

Basically, there is a single thread of execution which pops callbacks from an event queue. However, the next function queued won't be called until the current one has finished and returned.

It's called asynchronous because the system doesn't block on I/O. Instead, you register a listener and wait until the system notifies you. The system will process other events until the I/O operation finishes so it will keep itself busy.

edit. I hadn't understood your question. I hope this edit addresses it.

It really depends on what you are doing. If you want to allow multiple simultaneous executions of doSomethingStateful then using an internal state object is definitely the way to go.

Otherwise if for some reason you can only handle one call at a time, take a look at something like Async.js for a function queue implementation.

like image 121
MBlanc Avatar answered Mar 16 '26 01:03

MBlanc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!