Created
July 2, 2020 01:10
-
-
Save jaawerth/d7e2a520aef84e17a0e73a297f7ddd7b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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