Adam
Adam

Reputation: 20882

node.js - ensuring one event occurs before another

I'm new to node.js and learning...

I have the following 2 socket.io listeners and I need to ensure the .on happens before the .once (currently the .once occurs first):

io.on('connection', function (socket) {

io.once('connection', function (socket) {

is there a good way to ensure the .once occurs fist always?

Upvotes: 0

Views: 177

Answers (2)

Peter Lyons
Peter Lyons

Reputation: 146004

So when you have these order dependencies, it's best to code for them explicitly. Events are great when operations are truly independent, but when operations have interdependencies, better to make that obvious in code. In general, don't assume anything about the order in which event sources will invoke the bound event handler functions. Therefore, try something like this pseudocode:

io.on('connection', firstConnection);

function firstConnection(socket) {
    //do first connectiony stuff here
    io.on('connection', allConnections);
    io.off('connection', firstConnection);
    allConnections(socket);
}

function allConnections(socket){ /*all connectiony stuff here */}

Upvotes: 2

Brandon
Brandon

Reputation: 10028

This may not work because you are creating two independent functions. Usually, for event listeners, that is good. In this case, you need them coupled.

What you can do is subscribe using on and have the handler figure out if it has run before or not.

io.on('connection', function (socket) {
  if (!this.called) {
    // do what you want to do only the first time

    this.called = true;
  }

  // do whatever you want to do every time
}.bind({ called: false });

This creates a wrapper function which keeps track of whether or not it has been called and does something special when it is called for the first time.

Upvotes: 3

Related Questions