Orkun
Orkun

Reputation: 7228

Chaining calls without async nodejs

In the codebase i picked up, we have such chains as

funcA(a,b){

  funcB(a, funcC);
}

funcB(a,b,callback){

  callback(a, funcD); // calls funcC
}

funcC(a,b,callback){

  callback(a, funcE); // calls funcD
}

So the functions donT even know what they are calling as callback!..

Needless to say that it s really difficult to read follow this code..

Does it have to be this way? How can I improve this code?

Thanks!

Upvotes: 0

Views: 66

Answers (1)

localghost
localghost

Reputation: 142

Can the EventEmitter help you with your issue?

http://nodejs.org/api/events.html#events_emitter_on_event_listener

var emitter = require('events').EventEmitter;

function A(a,b) {
    // hard work
    emitter.emit('funcADone', a , b);
}

function B(a,b) {
    var c = a + b;
    emitter.emit('funcBDone', c);
}

function C(c) {
    console.log(c);
}

emitter.on('funcADone', B);
emitter.on('funcBDone', C);

A(1,2);

Upvotes: 2

Related Questions