Skip to content

Instantly share code, notes, and snippets.

@dmitry-tuzenkov
Last active November 18, 2021 10:57
Show Gist options
  • Save dmitry-tuzenkov/dce5582bc654898ea0574071192b1759 to your computer and use it in GitHub Desktop.
Save dmitry-tuzenkov/dce5582bc654898ea0574071192b1759 to your computer and use it in GitHub Desktop.
Nodejs simple es6 'promisify' function
/* eslint-disable indent */
/**
* Create a promise wrapper for function(err, arg1, ...argN)
* @param {function} fn - Function that should be promisified
* @returns {function} - Promisified function fn wrapper
* @example <caption>Example usage of promisify.</caption>
* const asynFn = require(...) // asynFn((err, a, b) => { ... })
* const pMyFn = promisify(asynFn)
* console.log('asynFn result', await pMyfn(1, 2))
*/
const promisify =
(fn) =>
(...args) => {
return new Promise((resolve, reject) => {
fn(...args, (err, ...args2) => (err ? reject(err) : resolve(...args2)))
})
}
module.exports = { promisify }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment