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
Published to https://github.com/OliverJAsh/nodeify-function/blob/master/node.js.