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.
You may also like fibers-promise and node-fiberize libraries.
Examples
Simply call asynchronous function synchronously:
var Sync = require('sync');
function asyncFunction(a, b, callback) {
process.nextTick(function(){
callback(null, a + b);
})
}
Sync(function(){
var result = asyncFunction.sync(null, 2, 3);
console.log(result);
var source = require('fs').readFile.sync(null, __filename);
console.log(String(source));
})
It throws exceptions!
var Sync = require('sync');
function asyncFunction(a, b, callback) {
process.nextTick(function(){
callback('something went wrong');
})
}
Sync(function(){
try {
var result = asyncFunction.sync(null, 2, 3);
}
catch (e) {
console.error(e);
}
})
Sync(function(){
var result = asyncFunction.sync(null, 2, 3);
return result;
}, function(err, result){
if (err) console.error(err);
console.log(result);
})
Transparent integration
var Sync = require('sync');
var MyNewFunctionThatUsesFibers = function(a, b) {
return a + b;
}.async()
var MyOldFashoinAppFunction = function() {
MyNewFunctionThatUsesFibers(2, 3, function(err, result){
if (err) return console.error(err);
console.log(result);
})
}
Sync(function(){
var result = MyNewFunctionThatUsesFibers(2, 3);
console.log(result);
var result = MyNewFunctionThatUsesFibers.sync(null, 2, 3);
console.log(result);
})
Parallel execution:
var Sync = require('sync'),
Future = Sync.Future();
Sync(function(){
try {
var foo = asyncFunction.future(null, 2, 3);
var bar = asyncFunction.future(null, 5, 5);
var baz = asyncFunction.future(null, 10, 10);
console.log(foo);
console.log(foo.result, bar.result, baz.result);
asyncFunction(2, 3, foo = Future());
console.log(foo);
console.log(foo.result);
}
catch (e) {
console.error(e);
}
})
Timeouts support
var Sync = require('sync'),
Future = Sync.Future;
function asyncFunction(a, b, callback) {
setTimeout(function(){
callback(null, a + b);
}, 1000)
}
Sync(function(){
var foo = asyncFunction.future(null, 2, 3);
foo.timeout = 500;
try {
var result = foo.result;
}
catch (e) {
console.error(e);
}
asyncFunction(2, 3, foo = new Future(500));
try {
var result = foo.result;
}
catch (e) {
console.error(e);
}
})
See more examples in examples directory.
Installation
install
$ npm install sync
and then
$ node your_file_using_sync.js