promised-callback
v1.2.3
Published
Little helper to make supporting async/await and callbacks a bit easier.
Downloads
6
Readme
____ _ _ _ __ __ _____ ___ _ _____
/ ___| / \ | | | | | \/ | ____| / _ \| |/ |__ \
| | / _ \ | | | | | |\/| | _| | | | | ' / / /
| |___ / ___ \| |___| |___ | | | | |___ | |_| | . \ |_|
\____/_/ \_|_____|_____| |_| |_|_____| \___/|_|\_\(_)
This snippet of code gives you an easy way to support all Big Three flow control styles:
- Callbacks with (err, data) convention
- Promises
- Await/async (this is what you've always wanted, just learn it)
It also gives you to()
function to nicely catch errors from promises without using
two gazillion try/catch blocks.
Here's your base function:
import promcall from 'promised-callback'
async function Foo(bar, callback) {
return await new Promise(async (resolve, reject) => {
// When you call `done(data)` or `error(err)`, promises will be kept
// and callbacks called. `await to(asyncFunc)` automatically catches errors from
// asyncFunc's promises.
const { done, error, to } = promcall(resolve, reject, callback)
[err, result] = await to(doTheThing())
err ? error(err) : done(result)
})
}
This little helper is meant to be forked by you if you want to add your own custom handling for errors etc.