Node.js和2个数据库的请求

时间:2013-08-30 09:47:10

标签: javascript database node.js sync

案例: 两个函数,function1返回不完整的数据,因为function2没有完成。

Var db; // connection to first database
Var db2; // connection to other database
Var user;
Function1 = function(user_id) { 
  Db.query("SELECT variable1 FROM tbl_db WHERE user_id = '"+ user_id +"'").success(function(response) {
    user.id = user_id;
    user.v1 = variable1;
    console.log(user); // log1
    var variables = function2(variable1, user_id);
    console.log(variables); //  log2
    user.x = variables.x;
    user.y = variables.y;

    console.log(user); // log3
    return user;
  });
}
function2 = function(val, user_id) {
  // connection to other database
  Db2.query("SELECT x,y FROM tbl_db2 WHERE val = '"+ val +"' AND user_id = '"+ user_id +"' ").success(function(response) {
    console.log(response); // log4
    return response;
  });
}

// start
function1(123);

//log1 variable
//log2 undefined
//log3 not correct user
//log4 variable2

我需要

//log1 variable
//log4 variable2
//log2 variable2
//log3 correct user

我的职能有什么问题? 我读到了异步但我无法举例说明第一个函数将变量作为参数发送给下一个函数。

1 个答案:

答案 0 :(得分:0)

使用回调。像这样的东西 -

Var db; // connection to first database
Var db2; // connection to other database
Var user;
function1 = function(user_id) { 
  Db.query("SELECT variable1 FROM tbl_db WHERE user_id = '"+ user_id +"'").success(function(response) {
    user.id = user_id;
    user.v1 = variable1;
    console.log(user); // log1
    function2(variable1, user_id, function(variables) {
      console.log(variables); //  log2
      user.x = variables.x;
      user.y = variables.y;

      console.log(user); // log3
      return user;
    });
  });
}

function2 = function(val, user_id, callback) {
  // connection to other database
  Db2.query("SELECT x,y FROM tbl_db2 WHERE val = '"+ val +"' AND user_id = '"+ user_id +"' ").success(function(response) {
    console.log(response); // log4
    callback(response);
  });
}

// start
function1(123);