Skip to content

Commit ac9e4c9

Browse files
committed
feat: add utility helper for returning promises or using callbacks
1 parent d4e12db commit ac9e4c9

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

lib/utils.js

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -693,6 +693,42 @@ function* makeCounter(seed) {
693693
}
694694
}
695695

696+
/**
697+
* Helper function for either accepting a callback, or returning a promise
698+
*
699+
* @param {Function} [callback] an optional callback.
700+
* @param {Function} fn A function that takes a callback
701+
* @returns {Promise|void} Returns nothing if a callback is supplied, else returns a Promise.
702+
*/
703+
function maybePromise(callback, fn) {
704+
let result;
705+
if (typeof callback !== 'function') {
706+
result = new Promise((resolve, reject) => {
707+
callback = (err, res) => {
708+
if (err) return reject(err);
709+
resolve(res);
710+
};
711+
});
712+
}
713+
714+
fn(function(err, res) {
715+
if (err != null) {
716+
try {
717+
callback(err);
718+
} catch (error) {
719+
return process.nextTick(() => {
720+
throw error;
721+
});
722+
}
723+
return;
724+
}
725+
726+
callback(err, res);
727+
});
728+
729+
return result;
730+
}
731+
696732
module.exports = {
697733
filterOptions,
698734
mergeOptions,
@@ -722,5 +758,6 @@ module.exports = {
722758
MongoDBNamespace,
723759
resolveReadPreference,
724760
emitDeprecationWarning,
725-
makeCounter
761+
makeCounter,
762+
maybePromise
726763
};

0 commit comments

Comments
 (0)