Last active
August 29, 2015 14:23
-
-
Save gr0uch/76abf344bbaaf3c7cf3f to your computer and use it in GitHub Desktop.
Use callback middleware functions as promises.
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
import promiseMiddleware from './promise_middleware' | |
import http from 'http' | |
import cors from 'cors' | |
http.createServer(async function (request, response) { | |
const middleware = promiseMiddleware.bind(null, request, response) | |
try { | |
await middleware((request, response, next) => next()) | |
await middleware(cors()) | |
} | |
catch (error) { | |
response.statusCode = 500 | |
return response.end(`Oops, an error occured.`) | |
} | |
response.end(`Hello world!`) | |
}).listen(1337) |
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 callback middleware functions as promises. | |
* | |
* @param {Error} [error] | |
* @param {Object} request | |
* @param {Object} response | |
* @param {Function} middleware | |
*/ | |
export default function promiseMiddleware () { | |
return new Promise((resolve, reject) => | |
// The last argument is the middleware function, let's invoke it. | |
arguments[arguments.length - 1]( | |
// Exclude the last argument, invoke the middleware function with the | |
// passed in arguments as positional arguments using the spread operator. | |
...Array.prototype.slice.call(arguments, 0, -1), | |
// This is the `next` function expressed succinctly as an arrow function. | |
// If it's called without an argument, it resolves the promise. | |
error => error ? reject(error) : resolve())) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment