Nodeify the result of a promise returning function.
When an API requires that you pass it a function with the signature (...args, cb)
, wrap is a small helper that allows you to instead pass a promise returning function. wrap will nodeify the result of the promise returning function (fulfilment or rejection) by passing its value to the original callback.
One such API that asks for an asynchronous listener function (...args, cb)
is express. When a HTTP request is made, express will call your listener function, if you have one registered for that route. The example below demonstrates how wrap can help you to use promises in such a situation.
// 1. The traditional callback (next)
app.get('/', (req, res, next) => {
next(new Error('Example error'));
});
// 2. If you want to use promises, you must remember to manually nodeify. That
// it to say, "call the callback with the result of the promise (fulilment
// or rejection)."
app.get('/', (req, res, next) => {
return Q.reject(new Error('Example error'))
.nodeify(next);
});
// 3. wrap nodeifies the promise for you.
app.get('/', wrap((req, res) => {
return Q.reject(new Error('Example error'));
}));
To run the express example:
npm install
node traceur-runner.js express-example.js
Very fair points.
I've just had a go at writing an adapter for
express.Router
. It's proving quite difficult, although mostly because it requires that I understand exactly howexpress.Router
works (so I can mimic its interface for the adapter). In many cases when you don't have enough understanding about how a third party API works, it's easiest to fix it at the call site (as I'm proposing above).I'm not really convinced it's worth trying to write a fully working
express.Router
adapter, given that I don't know enough about the required interface. Here's what I started with anyway: