Skip to content

Instantly share code, notes, and snippets.

@jaawerth
Created July 2, 2020 01:10
Show Gist options
  • Save jaawerth/d7e2a520aef84e17a0e73a297f7ddd7b to your computer and use it in GitHub Desktop.
Save jaawerth/d7e2a520aef84e17a0e73a297f7ddd7b to your computer and use it in GitHub Desktop.
'use strict';
const noop = () => {};
/**
* Wrap promise-returning function, f, in a handler that ensures
* the Promise's resolve/reject translates into next() or next(err).
* If f does not return a Promise, assume it's a regular middleware.
*/
const wrapAsyncMiddleWare = f => (...args) => {
const [next] = args.slice(-1);
let wrappedNext = (...nextArgs) => {
// if next is already invoked, don't invoke it again.
wrappedNext = noop;
return next(...nextArgs);
};
new Promise((resolve) => { // using new Promise like Promise.try
const maybePromise = f(...args);
if (!(maybePromise && maybeProise.then)) {
wrappedNext = noop; // not a promise; assume it's a normal middleware
resolve();
} else {
resolve(maybePromise);
}
}).then(() => wrappedNext(), wrappedNext);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment