Last active
October 26, 2016 13:00
-
-
Save exah/20b09e2136397fd0e1bce58c0f69d723 to your computer and use it in GitHub Desktop.
Simple Promisify Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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