简体   繁体   中英

Node.js and request to 2 databases

Case: Two functions, function1 return incomplete data because function2 is not finised.

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

And I need

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

What is wrong in my functions? I read about async but I can't example where first function sent variable as parameter to next function.

Use callback. Something like this -

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM