多个回调,带有一个响应-Node JS

时间:2015-02-15 16:36:52

标签: javascript node.js callback

我收到来自客户端的请求,请求需要从两个表中选择数据,从一个表我需要在表2中选择1000个记录我只需要选择两个记录,通过回调处理它。我想要在两个回调函数执行后需要发送给我的客户端的响应,如何在节点js中实现这一点?

2 个答案:

答案 0 :(得分:0)

欢迎回调地狱!你只需要构建pyramide表单回调!

示例:

function getDataFromDB (query, successCb, errorCb) {
    executeFirstQuery(query, function(firstQueryData) {
        console.log('First query ok! Now execute second.');

        executeSecondQuery(query, function(secondQueryData) {
            console.log('Second query ok! Now execute successCb().');

            successCb([firstQueryData, secondQueryData]);
        }, function(error) {
            errorCb("Error in second query");
        })
    }, function(error) {
        errorCb("Error in first query");
    });
}

function executeFirstQuery (query, successCb, errorCb) {
    console.log("Execute first query!");
    successCb("Some data from first query");
    // errorCb("Some Error from first query");
}

function executeSecondQuery (query, successCb, errorCb) {
    console.log("Execute second query!");
    successCb("Some from second query");
    // errorCb("Some Error from second query");
}

getDataFromDB("Some sql", function(data) {
    console.log(data);
}, function(error) {
    console.error(error);
});

或使用Promises:http://documentup.com/kriskowal/q/

答案 1 :(得分:0)

您有以下选项:

  1. 遵循节点样式回调模式。另请阅读Callback-hell
  2. 关注promises
  3. 回调模式

    var f  = function(somedata, cb){
        // pick user from db
        pickUserFromTable1(somedata, function(err, users){
            // callled on completion of pickUserFromDB
            if(err){
                //handle error.
                cb(err, null);
                return;
            }
    
            pickUserFromTable2(users, function(err, finallySelectedUsers){
                // called on completion of pickUserFromTable2
                if(err){
                    // handle error.
                    cb(err, null);
                    // returning is important. or use else part of if to separate the case
                    return;
                }
    
                // call initiator's callback function on completion of both pickUserFromTable1 and pickUserFromTable2
                cb(null, finallySelectedUsers);
            });
        })
    }
    

    注意:这种方法适用于短项目,但如果依赖链冗长,则会导致一些维护问题(回调地狱)。