es-promise-ext
Version:
Native promise extensions for javascript and typescript.
41 lines (40 loc) • 1.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = wrap;
/**
* Starts a promise with an asynchronous function that use a callback.
*
* @param {WrappedAsyncFunction<U>} wrappedAsyncFunctionWithCallback
* - An asynchronous function that will be called, returning a result in callback.
*
* @return {Promise<U>}
* The result returned from callback.
*
* @example
* promiseWrap(asyncFunction);
* // for asyncFunction accepting the callback as 1st parameter
*
* promiseWrap(cb => asyncFunction(1, 2, cb));
* // for other asyncFunction accepting the callback as the rest parameter
*/
function wrap(wrappedAsyncFunctionWithCallback) {
if (typeof wrappedAsyncFunctionWithCallback !== 'function') {
throw new TypeError('Promise.wrap parameter 1 must be a function');
}
return new Promise((resolve) => {
const callback = function (...args) {
switch (args.length) {
case 0:
resolve(undefined);
break;
case 1:
resolve(args[0]);
break;
default:
resolve(args);
break;
}
};
wrappedAsyncFunctionWithCallback(callback);
});
}