Skip to content

Instantly share code, notes, and snippets.

@exah
Last active October 26, 2016 13:00
Show Gist options
  • Save exah/20b09e2136397fd0e1bce58c0f69d723 to your computer and use it in GitHub Desktop.
Save exah/20b09e2136397fd0e1bce58c0f69d723 to your computer and use it in GitHub Desktop.
Simple Promisify Function
// Compact version
const promisify = (fn, ...args) => new Promise((resolve, reject) =>
fn(...args, (error, result) => error && reject(error) || resolve(result))
)
// Example
// function myAsyncFn(options = Object, callback = Function) {}
// Like Promise
promisify(myAsyncFn, { msg: 'test' }).then(result => console.log(result))
promisify(cb => myAsyncFn({ msg: 'test' }, cb)).then(result => console.log(result)) // Same
// Or inside async/await function
async function example() {
const result = await promisify(cb => myAsyncFn({ msg: 'test' }, cb))
console.log(result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment