Introduction
node-sync is a simple library that allows you to call any asynchronous function in synchronous way. The main benefit is that it uses javascript-native design - Function.prototype.sync function, instead of heavy APIs which you'll need to learn. Also, asynchronous function which was called synchronously through node-sync doesn't blocks the whole process - it blocks only current thread!
It built on node-fibers library as a multithreading solution.
Examples
Simply call asynchronous function synchronously:
var Sync = ; { process} // Run in a fiber
It throws exceptions!
var Sync = ; { process} // Run in a fiber // Or simply specify callback function for Sync fiber// handy when you use Sync in asynchronous environment
Transparent integration
var Sync = ; var { // <-- no callback here // we can use yield here // yield(); // or throw an exception! // throw new Error('something went wrong'); // or even sleep // Sync.sleep(200); // or turn fs.readFile to non-blocking synchronous function // var source = require('fs').readFile.sync(null, __filename) return a + b; // just return a value } // <-- here we make this function friendly with async environment // Classic asynchronous nodejs environmentvar { // We just use our MyNewFunctionThatUsesFibers normally, in a callback-driven way } // From fiber environment
Parallel execution:
var Sync = Future = Sync; // Run in a fiber
Timeouts support
var Sync = Future = SyncFuture; { } // Run in a fiber
How to address non-uniform callbacks
Sometimes third-party libraries are not following convention and passing multiple result parameters to the callback, e.g. callback(err, recordsets, returnValue)
. In this situation, node-sync
will simply return array of values instead of value.
// Asynchronous which returns multiple arguments to a callback and returning a value synchronously { process}
See more examples in examples directory.
Installation
install
$ npm install sync
and then
$ node your_file_using_sync.js