Skip to content

Commit

Permalink
Add promisify method
Browse files Browse the repository at this point in the history
  • Loading branch information
JacksonTian committed Mar 28, 2017
1 parent 244f6ae commit e7f2715
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion lib/index.js
Expand Up @@ -129,7 +129,7 @@ exports.getYYYYMMDD = function (date) {

/**
* sleep a while.
* @param {Number} in milliseconds
* @param {Number} ms in milliseconds
* @return {Promise} a Promise
*/
exports.sleep = function (ms) {
Expand All @@ -138,6 +138,32 @@ exports.sleep = function (ms) {
});
};

/**
* Wrap a standard async API to a promise-based API.
* ```js
* const readFile = kitx.promisify(fs.readFile);
* readFile(file).then((data) => {
* // data
* }, (err) => {
* // error
* });
* ```
* @param {Function} fn a strandard async API
* @return {Function} a Promise-based function
*/
exports.promisify = function(fn) {
return function (...args) {
return new Promise((resolve, reject) => {
fn(...args, function (err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
};
};

/**
* Get the IPv4 address
* @return {String} the IPv4 address, or empty string
Expand Down

0 comments on commit e7f2715

Please sign in to comment.