0

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 ?

3
  • You can do this by having your async code check for all 3 situations when your async code resolves. Eg, let's pretend you're doing an ajax call. When the call returns the data (or an error), you'll have to check for each event you support and warn your event mediator about it. If it returns an error, trigger the 'error' event, if it returns data, trigger the 'dt' event etc. Personally, I switched to promises after getting fed up with keeping app state consistent through multiple event calls. Commented Aug 24, 2015 at 17:10
  • how i will trigger an event i am not sure about that can you please write as answer with example i can select as solution then Commented Aug 24, 2015 at 17:16
  • The answer below contains a nice example of the builtin node mediator. Commented Aug 24, 2015 at 17:18

1 Answer 1

2

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

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

2 Comments

this is the solution i guess but still have some questions :) how i can return multipple values for one event and can i return object for example for loading let it be a file upload sometyhing like on("ld",function(expected,received))
you cannot return multiple values, but you can wrap them into single object. as in third emit i wrote

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.