node.js - Simple flow control in NodeJs -
i've read through number of examples , tutorials , although know solution simple can't brain wrapped around it. here appreciated.
i have 2 functions in node. functiona() takes no arguments , returns string in english. second, functionb(english) takes english string returned funcitona() , translates language.
i believe callback best solution here life of me can't figure out best structure be.
thanks in advance.
i'm little unclear you're looking (you might overthinking things) consider following illustrates 4 ways of these functions being called , calling amongst themselves. clarification, should note not writing node-style callbacks, take form callback(err,result) in err evaluates false if there no error. don't have write own callbacks way, although tend myself.
// 'functiona' function getmessage(){ return 'hello'; }; // 'functionb' function francofy(str) { var result; switch(str){ case 'hello': result = 'bon jour'; // 'allo' might better choice, let's stick node break; default: throw new error('my vocabulary limited'); } return result; }; // straightforward use of these functions console.log('synch message, synch translate', francofy(getmessage())); // if translation asynch - example, you're calling off api // let's simulate api delay settimeout function contemplatetranslation(str,cb) { settimeout(function(){ var result = francofy(str); cb(result); },1000); }; contemplatetranslation(getmessage(), function(translated){ console.log('synch message, asynch translate: ' + translated); }); // if message async? function getdelayedmessage(cb) { settimeout(function(){ cb('hello'); },1000); }; getdelayedmessage(function(msg){ console.log('asynch message, synch translate', francofy(msg)); }); // if need call asynchronous api message , // call asynchronous api translate it? getdelayedmessage(function(msg){ contemplatetranslation(msg, function(translated){ console.log("my god, it's full of callbacks", translated); }); });
note there other ways deal asynchronous operations, such promises (i prefer q promise library myself, there other options). however, worth understanding core behavior before overlay abstractions on it.
Comments
Post a Comment