Skip to content

Instantly share code, notes, and snippets.

@wmakeev
Last active July 19, 2017 11:43
Show Gist options
  • Save wmakeev/dbdf1a4c997c7f127969972c5b906076 to your computer and use it in GitHub Desktop.
Save wmakeev/dbdf1a4c997c7f127969972c5b906076 to your computer and use it in GitHub Desktop.
Promisefy.js #promise #tools
'use strict'
function promisefyFunction (func, context) {
return function () {
let args = Array.prototype.slice.call(arguments, 0)
return new Promise(function (resolve, reject) {
var cb = function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
}
func.apply(context, args.concat([cb]))
})
}
}
module.exports = function promisefy (methods, context) {
if (typeof methods === 'function') {
return promisefyFunction(methods, context)
} else if (methods instanceof Array) {
if (!context) {
throw new Error('context must to be defined with array of methods')
}
return methods.reduce(function (res, m) {
res[m] = promisefyFunction(context[m], context)
return res
}, {})
} else {
throw new Error('method must to be array or function')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment