Parallel function calls in Node.js

前端 未结 2 1002
暗喜
暗喜 2020-12-30 12:45

I need to do a few independent database queries in Node.js. After all queries are executed, response should be sent. My first try looks like this:

templateDa         


        
相关标签:
2条回答
  • 2020-12-30 13:18

    You could just use a function that checks if all the data is present as your callback to your queries, and if all the data is present then the response could be sent. So something like

    function checkData(){
        if (templateData.A && templateData.B && templateData.C){
            //send your response
        }
    }
    

    then just don't nest your calls

    model.getA(function(result){
        templateData.A = result;
        checkData();
    }
    
    model.getB(function(result){
        templateData.B = result;
        checkData();
    }
    
    model.getC(function(result){
        templateData.C = result;
        checkData();
    }
    

    When all three have completed your response will be sent.

    0 讨论(0)
  • 2020-12-30 13:24

    Use the async package: (npm install async)

    async.parallel([
        function(){ ... },
        function(){ ... }
    ], callback);
    

    https://github.com/caolan/async#parallel

    Alternatively, you can use promises:

    Q.spread(
        [ model.getA(), model.getB(), model.getC() ],
        function(a, b, c) {
            // set templateData
            return templateData;
        }
    ).then(...);
    

    (assuming that the get*() methods return promises)

    0 讨论(0)
提交回复
热议问题