思考异步 - 不是一件容易的事 Node.js + Express.JS

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

提出以下问题是为了从您的回答中更好地理解在 Node.js

上开发时如何思考 "Async"

我有以下代码:

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();
}

我想了解如何更好地思考 "async" 而我需要等待对用户的响应,直到所有异步功能都结束。

我的问题是如何仅在 processRequest(paramsObj,next);

中的某些异步方法设置 paramObj.someVal 之后才执行 res.send(paramObj.someVal)

如果您需要等待 processRequest 的结果来设置 paramsObj.someVal,那么最终您需要处理该回调

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();
}

假设 processRequest() 的第二个参数是一个完成回调,您可以为该回调传递您自己的函数并在该自定义回调中执行您的 res.send(),如下所示:

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() {
            res.send(paramsObj.someVal);
        });

    }).catch(function(err){
        console.log(err);
        next(err);
    }).done();
}

既然你做了 res.send(...),我假设你不想在该代码路径中实际调用 next()