2016-10-23 121 views
0

我想從nodejs中的數據庫中檢索一些數據。 檢索這些數據是一個異步請求,因爲我們也是ajax請求。如何處理異步的ajax響應

Client.js

$.ajax('localhost/Server').done(function(){ 

}); 

Server.js

function cb(){ 
    // do stuff 
} 

// ajax request is going here 
function Server(req, res) { 
    GetTheModelFromTheDbInAsyncWay(function(cb){ 
     cb(); 
    }); 
} 

function GetTheModelFromTheDbInAsyncWay(cb) { 
    //doing stuff to the db e.g getting the result of a query 
    // ... 
    cb(result); 
} 

什麼技術,我需要使用,以獲取在我的異步Ajax請求aync服務器的請求? 我認爲它會像promised。 但我怎麼能傳回我的Ajax請求,因爲該數據庫請求是異步本身

希望我能搞清楚

回答

2

調用的說法你GetTheModelFromTheDbInAsyncWay作爲接收儘管它是一個功能。想必不是。你應該使用(例如,發送或從中通過res.send獲得的信息):

// ajax request is going here 
function Server(req, res) { 
    GetTheModelFromTheDbInAsyncWay(function(data){ // Not `cb`, `data` 
    // Use `data` here to produce the response you send via `res` 
    }); 
} 
+0

哦,我覺得傾倒^^ – xhallix

+1

@xhallix:我們都在那裏。 :-) –

+0

將盡快接受 – xhallix