deferinfer
v1.0.1
Published
Alternative converter between promises and callbacks
Downloads
4
Maintainers
Readme
deferinfer
Alternative converter between promises and callbacks
installation
npm install deferinfer
# -- or --
yarn add deferinfer
const { defer, infer } = require('promise-util')
// -- or --
const defer = require('promise-util').defer
defer(callback)
-> Promise
Convert callback function into to promise
const result = await defer(done => someCallbackFunction(done))
Properly forwards error
defer(done => {
done(new Error()) // forwarded to .catch()
throw new Error() // forwarded to .catch()
done(null, 42) // forwarded to .then()
})
.then(console.log)
.catch(console.error)
Async method support
defer(async done => {
const result = await anotherPromise()
done(null, result)promise-util
})
infer(promise, callback)
-> Promise
Convert promise to callback
const p = infer(Promise.resolve(42), (err, res) => {
if (err) console.error(err)
else console.log(res)
})
Define promise/callback agnostic functions
function add(a, b, callback) {
const promise = defer(done => {
done(null, a + b)
})
return infer(promise, callback)
}
add(5, 7, (err, sum) => {
console.log(sum) // => 12
})
const sum = await add(6, 4)
console.log(sum) // => 10