Ambi
Execute a function ambidextrously (normalizes the differences between synchronous and asynchronous functions). Useful for treating synchronous functions as asynchronous functions (like supporting both synchronous and asynchronous event definitions automatically).
Install
Backend
- Install Node.js
npm install --save ambi
Frontend
- See Browserify
Usage
Example
var ambi = require('ambi');
var result;
var syncMethod = function(x,y){
return x*y;
};
var asyncMethod = function(x,y,next){
return setTimeout(function(){
next(null,x*y);
},0);
};
result = ambi(syncMethod, 5, 2, function(err,result){
console.log(err, result);
});
console.log(result);
result = ambi(asyncMethod, 5, 2, function(err,result){
console.log(err, result);
});
console.log(result);
Notes
- Ambi accepts the arguments
(method, args...)
method
is the function to executeargs...
is the arguments to send to the method
- the last argument is expected to be the completion callback
- the completion callback is optional, but if defined, is expected to have the signature of
(err, results...)
- If the method has the same amount of arguments as those ambi received, then we assume it is an asynchronous method and let it handle calling of the completion callback itself
- If the method does not have the same amount of arguments as those ambi received, then we assume it is a synchronous method and we'll call the completion callback ourselves
- If the synchronous method throws an error or returns an error, we'll try to call the completion callback with a single
err
argument - If the synchronous method executes without error, we'll try to call the completion callback with a
err
argument equal to null, and a result
argument equal to the returned result of the synchronous method
- Ambi can also introspect a different method than the one it fires, by passing
[methodToFire, methodToIntrospect]
as the method
argument
History
You can discover the history inside the History.md file
License
Licensed under the incredibly permissive MIT License
Copyright © 2013+ Bevry Pty Ltd
Copyright © 2011-2012 Benjamin Arthur Lupton