John John - 3 months ago 10
Javascript Question

nodejs promise then with only one paramter opposed to 2

This is the call to a controller in a routes file from a nodejs application running express witha promise based api.

router.post('/create-user', function(req, res) {
CreateUserController.createUser( req.body.username, req.body.username ).then( res.jsonSuccess, res.jsonFail );
});


As you can see the end result of a resolved callback above hits res.jsonSuccess and the reject (the 2nd param in the
then
function) hits the res.jsonFail.

res.jsonSuccess & res.jsonFail are custom middlewares for this project and simply format and log data accordingly.

My question: I want to simplify this further. Is it possible to pass one parameter to the
then()
that could handle both the resolve and reject?

For example

router.post('/create-user', function(req, res) {
CreateUserController.createUser( req.body.username, req.body.username ).then( res.jsonOutDecide );
});

Answer

Is it possible to pass one parameter to the then() that could handle both the resolve and reject?

No.

What you want to do instead is to define a function that you can pass the promise to:

function jsonPromise(res, p) {
    return p.then(res.jsonSuccess, res.jsonFail);
}

so that you can do

router.post('/create-user', function(req, res) {
    jsonPromise( res, CreateUserController.createUser( req.body.username, req.body.username ) );
});

Even more elaborate would be to take the whole promise-returning function and decorate it:

function jsonResponse(f) {
    return function(req, res) {
        Promise.resolve(req).then(f).then(res.jsonSuccess, res.jsonFail);
        // similar to `f(req).…`, but catching exceptions and allowing plain return values
    };
}

router.post('/create-user', jsonResponse(function(req) {
    return CreateUserController.createUser( req.body.username, req.body.username );
}));