Skip to content

Commit

Permalink
feat: add utility helper for returning promises or using callbacks
Browse files Browse the repository at this point in the history
  • Loading branch information
mbroadst committed Feb 14, 2020
1 parent d4e12db commit ac9e4c9
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,42 @@ function* makeCounter(seed) {
}
}

/**
* Helper function for either accepting a callback, or returning a promise
*
* @param {Function} [callback] an optional callback.
* @param {Function} fn A function that takes a callback
* @returns {Promise|void} Returns nothing if a callback is supplied, else returns a Promise.
*/
function maybePromise(callback, fn) {
let result;
if (typeof callback !== 'function') {
result = new Promise((resolve, reject) => {
callback = (err, res) => {
if (err) return reject(err);
resolve(res);
};
});
}

fn(function(err, res) {
if (err != null) {
try {
callback(err);
} catch (error) {
return process.nextTick(() => {
throw error;
});
}
return;
}

callback(err, res);
});

return result;
}

module.exports = {
filterOptions,
mergeOptions,
Expand Down Expand Up @@ -722,5 +758,6 @@ module.exports = {
MongoDBNamespace,
resolveReadPreference,
emitDeprecationWarning,
makeCounter
makeCounter,
maybePromise
};

0 comments on commit ac9e4c9

Please sign in to comment.