diff --git a/lib/utils.js b/lib/utils.js index dd6cbe8ce8..ed50a5d9ab 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -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, @@ -722,5 +758,6 @@ module.exports = { MongoDBNamespace, resolveReadPreference, emitDeprecationWarning, - makeCounter + makeCounter, + maybePromise };