Search code examples
javascriptnode.jsdesign-patternsasynchronousevent-driven-design

Writing Async code in event driven way


I am programminfg in node.js sometimes async functions become really incredibly dirty. I want to write async code but retrieve data as an event happens i am aware of promises but it is not exactly what i want simply what i ask is something like this

asyncFunc(error,dt,ld){
//some async code such as db operations
}

then i want to fetchj the data in event way

asyncFunc.on("dt",function(dt){do something});
asyncFunc.on("error",function(err){i have an error object});
asyncFunc.on("ld",function(ls){loading});

is there any way to do this i know promises and some 3rd party libraries against callback hell but my question is especially in that way i wrote how i can design my code ?


Solution

  • Use nodejs events

    var asyncFunc = function(error,dt,ld){
        var events = require('events');
        var eventEmitter = new events.EventEmitter();
    
        //emit error
        eventEmitter.emit('error', new Error('some error'));
        //emit dt
        eventEmitter.emit('dt', 'some data for dt');
        //emit dld
        eventEmitter.emit('ld', {message: 'some details for ld', ld: ld});
        return eventEmitter;
    }
    
    //then
    asyncFunc.on("dt",function(dt){/*do something*/});
    asyncFunc.on("error",function(err){/*i have an error object*/});
    asyncFunc.on("ld",function(ls){/*loading*/});
    

    Great article here
    Official nodejs event docs