Search code examples
node.jsexpressnode-async

Thinking Async - not an easy task Node.js + Express.JS


The following question is asked in order to better understand from your answers how to think "Async" when developing on Node.js

I have the following code:

router.get('/', function(req, res, next) {

    ... //Definition of rules and paramsObj

    //Validation that returns a promise 
    Indicative.validate(rules,paramsObj)

    .then(function(success){
        //we passed the validation. start processing the request

        //ProcessRequest has async calls but when all async functions are over, it sets paramObj.someVal with a calculated value.
        processRequest(paramsObj,next);

        //My problem is here. at this point paramsObj.someVal is not set yet. and therefore the response to the user will be incorrect.
        res.send(paramsObj.someVal);
    }).catch(function(err){
        console.log(err);
        next(err);
    }).done();
}

I wish to understand how to better think "async" while i need to wait with the response to the user until all async functions are over.

My question is how to execute res.send(paramObj.someVal) only after the paramObj.someVal is set by some async methods in processRequest(paramsObj,next);


Solution

  • If you need to wait on the result of processRequest for paramsObj.someVal to be set then ultimately you need to handle that callback

    router.get('/', function(req, res, next) {
    
        ... //Definition of rules and paramsObj
    
        //Validation that returns a promise 
        Indicative.validate(rules,paramsObj)
    
        .then(function(success){
            //we passed the validation. start processing the request
    
            //ProcessRequest has async calls but when all async functions are over, it sets paramObj.someVal with a calculated value.
            processRequest(paramsObj, function(err) {
                if (!err && !paramsObj.someVal) {
                    // raise a custom error if the value is not set
                    err = new Error('Value not set');
                }
                if (err) {
                    next(err);
                } else {
                    res.send(paramsObj.someVal);
                }
            });
    
        }).catch(function(err){
            console.log(err);
            next(err);
        }).done();
    }