javascript - Is it possible to handle both async and sync function results inside a sync function in node.js? -
i'm working on library pre-processes less, stylus, etc. preprocessors can both async , sync in nature. because result used in build stage, writing blocking code here not issue.
because preprocessors sync, , library expects sync functions down chain, wondering if it's somehow possible wrap preprocessor functions inside sync function can handle both sync , async results preprocessing function?
basically possible this, somehow?
syncfn = function(contents) { var res = syncorasyncfn(contents, function(err, contents) { res = contents }) // .. magic here waits results of syncorasyncfn return res; // return result function async or sync }
sorry, that's impossible. whenever block of code running nothing can run inbetween, i.e. there no real parallelism in nodejs. therefore whatever do: res = contents
line can fire after syncfn
finishes whatever does, i.e. after synchronous operations finish job in block of code.
this forces nodejs programmers use callback pattern, example:
syncfn = function(contents, callback) { syncorasyncfn(contents, function(err, contents) { callback(contents); }) }
Comments
Post a Comment