Last active
June 23, 2017 14:02
-
-
Save cvan/8f649c995f93b0187432 to your computer and use it in GitHub Desktop.
turn any callback function into a promise-based one
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
| var Promise = require('es6-promise').Promise; | |
| function promisify(func) { | |
| // Already a Promise. | |
| if (func && typeof func.then === 'function') { | |
| return func; | |
| } | |
| return function () { | |
| var args = Array.prototype.slice.apply(arguments); | |
| return new Promise(function (resolve, reject) { | |
| func.apply(this, args.concat(function (err, value) { | |
| if (err) { | |
| reject(err); | |
| } else { | |
| resolve(value); | |
| } | |
| })); | |
| }); | |
| }; | |
| } | |
| /* | |
| Sample usage: | |
| var Joi = require('joi'); // Using a library whose methods are promises. | |
| var validate = promisify(Joi.validate); // Wraps `Joi.validate` in a promise. | |
| or | |
| var phantom = require('node-phantom-simple'); | |
| phantom.create = utils.promisify(phantom.create); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment