2

I'm looking to fire off a function, but only when two or multiple events have fired. Is there a built in way to do this?

Here's with one event:

setup.on('api routes ready', function () {
  console.log('Yay!');
});

How can I do this:

setup.on('api routes ready', 'website routes ready', function () {
  console.log('Yay!');
});

Any ideas would be rockin'!

1
  • 1
    You probably will have to create a flag to show, when the first event has fired, so when the second event fires, you recognize this. Commented Nov 21, 2014 at 21:40

2 Answers 2

3

Best done with a library such as async which has appropriate functions.

With that, you can choose whether to execute your functions in parallel or in series and if in parallel, then you can define a callback that will only run after all functions are complete.

Whilst @HeadCode's code will work, it doesn't scale well and is easy to make a mistake.

Sign up to request clarification or add additional context in comments.

3 Comments

Question, are the types of things in async getting absorbed into node's eventEmitter class?
Good question. But I don't think so, they seem to want to keep Node itself pretty light. I guess it is really a different use case. The async and similar libraries are just convenience added on to the native async nature of Node. They massively simplify your own code. You could probably do this with events but I think it would be more complex.
I'm going through trying to do it myself, it's interesting, forces you to use JavaScript in some really strange and interesting ways. Closures, &&'s and so forth.
1

This is (an untested) start.

var waitForIt = (function(){
    var api_ready = false;
    var web_ready = false;
    return function(event){
        if (event === 'api routes ready'){
            api_ready = true;
        }
        if(event === 'web routes ready'){
            web_ready = true;
        }

        if(api_ready && web_ready){
            console.log('Yay!');
        }
    }
 })();

setup.on('api routes ready', function () {
    waitForIt('api routes ready');
});

setup.on('web routes ready', function () {
    waitForIt('web routes ready');
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.