promise-or-not
is a function decorator that can act as a middleman to perform operations on resulting data, even if the function initially returns a promise.
yarn add @fizzygalacticus/promise-or-not
|| npm i --save @fizzygalacticus/promise-or-not
Parameters:
fn
- The primary function you wish to runonData
- The function to call when data is receivedonError
- The function to call when an error occurrsreturnPromise
- Forces even synchronous functions to return aPromise
. This can be useful in situations where you may want to make multiple calls topromise-or-not
as I do in my savethis project.
For synchronous functions:
const promiseOrNot = require('@fizzygalacticus/promise-or-not');
const mySyncFn = i => 'some return value ' + i;
const decorated = promiseOrNot(mySyncFn, val => console.log(val));
const val = decorated(1); // will print `1`
console.log(val) // `1`
For asynchronous functions:
const promiseOrNot = require('@fizzygalacticus/promise-or-not');
const mySyncFn = i => Promise.resolve('some return value ' + i);
const decorated = promiseOrNot(mySyncFn, val => console.log(val));
decorated(1).then(console.log); // will print `1` twice
This was initially written for my trythis library, which just prints the return value of a wrapped function (such as the example above). I then realized that this would be very handy to abstract away for other, potentially similar use cases.