2015-10-06 111 views
1

我剛開始研究node.js並瞭解它的概念,我在理解回調方面遇到了一些麻煩,我試圖做的是調用函數getUserBranch( )中的函數getOffers()Node.js獲取函數的返回值

我讀到,因爲node.js異步性質,它更好地使用回調函數來獲取所需的數據,一旦完成執行完成。

現在我無法獲取該getUserBranch正在恢復,我有沒有合適的想法如何做到這一點,以及回調函數的值,但我如何才能從那裏值的價值?

file2.js

var getUserBranch = function(email,callback) { 


client.execute('SELECT * from branch WHERE email=?', [ email ], function(
     err, data, fields) { 
    if (err) 

     console.log("error"); 
    else 
     console.log('The solution is in branch: \n', data); 
    res = data.rows[0]; 
    return callback(res); 
}); 

} 

file1.js

var getOffers = function (email) { 

    var branchObj = require('./file2.js'); 
    var branchList = branchObj.getUserBranch(email,getList)); 
    return branchList; 
}; 

var getList = function(res){ 
    var results=res; 
    return results; 
} 

回答

1

與堆棧中的回調函數異步調用的工作。看看這個:

var getUserBranch = function(email,callback) { 
    client.execute('SELECT * from branch WHERE email=?', [ email ], function(err, data, fields) { 
     if (err) 
      console.log("error"); 
     else{ 
      console.log('The solution is in branch: \n', data); 
      /* This data stack 3 */ 
      callback(data.rows[0];); 
     } 
    }); 
}; 

var getOffers = function (email, callback) { 
    var branchObj = require('./file2.js'); 
    branchObj.getUserBranch(email, function(data){ 
     /* This data stack 2 */ 
     callback(data); 
    }); 
}; 

function anyFunction(){ 
    getOffers("[email protected]", function(data){ 
     /* This data stack 1 */ 
     console.log(data); 
    }); 
} 
+0

That worked :) Thank you – user3048440