tramway-callback-adapter
v1.0.0
Published
A simple callback adapter that permits backward compatibility as the project moves toward async/await
Downloads
9
Readme
Tramway Callback Adapter is a simple backwards compatible wrapper to allow code using callbacks to adapt to future async/await implementations in a Tramway project built in ES2015+. Furthermore, its intent is to reduce the clutter associated with conditionally returning callbacks in the new try-catch syntax.
Installation:
npm install tramway-callback-adapter
Documentation
CallbackAdapter.executeAsyncAsCallback
| Parameter | Type | Usage | | --- | --- | --- | | cb | function | The callback function that's expected to be invoked | | func | AsyncFunction | The async function that will be called | | ...args | ...any | The arguments that will be passed to the async function |
Example usage
Imagine you have a class that handles some asynchronous operation and is expected to return a response as a callback but it will use a new async function to get the data. Wrapping the async function's call with the executeAsyncAsCallback method will wrap the response into a callback invocation.
import CallbackAdapter from 'tramway-callback-adapter';
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
class Test {
execute(cb) {
CallbackAdapter.executeAsyncAsCallback(cb, this.someAsyncFunc, 1, 5);
}
async someAsyncFunc(arg1, arg2) {
await timeout(3000);
return arg1 + arg2;
}
}
let a = new Test();
//outputs null, 6
a.execute((err, res) => {console.log(err, res)});