thenify
Promisify a callback-based function using any-promise
.
- Preserves function names
- Uses a native promise implementation if available and tries to fall back to a promise implementation such as
bluebird
- Converts multiple arguments from the callback into an
Array
, also support change the behavior byoptions.multiArgs
- Resulting function never deoptimizes
- Supports both callback and promise style
An added benefit is that throw
n errors in that async function will be caught by the promise!
API
fn = thenify(fn, options)
Promisifies a function.
Options
options
are optional.
-
options.withCallback
- support both callback and promise style, default tofalse
. -
options.multiArgs
- change the behavior when callback have multiple arguments. default totrue
.true
- converts multiple arguments to an arrayfalse
- always use the first argumentArray
- converts multiple arguments to an object with keys provided inoptions.multiArgs
-
Turn async functions into promises
var thenify = ; var somethingAsync = ;
- Backward compatible with callback
var thenify = ; var somethingAsync = ; // somethingAsync(a, b, c).then(onFulfilled).catch(onRejected);// somethingAsync(a, b, c, function () {});
or use thenify.withCallback()
var thenify = withCallback; var somethingAsync = ; // somethingAsync(a, b, c).then(onFulfilled).catch(onRejected);// somethingAsync(a, b, c, function () {});
- Always return the first argument in callback
var thenify = ; var promise = ; // promise().then(function onFulfilled(value) {// assert.equal(value, 1);// });
- Converts callback arguments to an object
var thenify = ; var promise = ; // promise().then(function onFulfilled(value) {// assert.deepEqual(value, {// one: 1,// tow: 2,// three: 3// });// });