Last active
July 19, 2017 11:43
-
-
Save wmakeev/dbdf1a4c997c7f127969972c5b906076 to your computer and use it in GitHub Desktop.
Promisefy.js #promise #tools
This file contains hidden or 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
'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