Is it possible to handle both async and sync function results inside a sync function in node.js?

Is it possible to handle both async and sync function results inside a sync function in node.js?

Problem

I’m working on a library that pre-processes less, stylus, etc. Preprocessors can be both async and sync in nature. Because the result will only be used in build stage, writing blocking code here is not an issue.

Because most preprocessors are sync, and the library expects sync functions down the chain, I was wondering if it’s somehow possible to wrap the preprocessor functions inside a sync function that can handle both sync and async results from a preprocessing function?

Basically would it be possible to do something like this, somehow?

syncFn = function(contents) {
  var res = syncOrAsyncFn(contents, function(err, contents) {
    res = contents
  })
  // .. do some magic here that waits for the results of syncOrAsyncFn
  return res; // Return the result from a function that could be async or sync
}
Problem courtesy of: ragulka

Solution

Sorry, that’s impossible. Whenever a block of code is running nothing can run inbetween, i.e. there is no real parallelism in NodeJS. Therefore whatever you do: res = contents line can only fire after syncFn finishes whatever it does, i.e. after all synchronous operations finish the job in a block of code.

This forces NodeJS programmers to use callback pattern, for example:

syncFn = function(contents, callback) {
  syncOrAsyncFn(contents, function(err, contents) {
    callback(contents);
  })
}
Solution courtesy of: freakish

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *