如何处理异步的ajax响应

时间:2016-10-23 16:26:21

标签: javascript jquery ajax node.js asynchronous

我想从nodejs中的数据库中检索一些数据。 检索这些数据是异步请求,就像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请求中的异步服务器请求? 我认为它会像promised。 但是我怎么能把它传回我的ajax请求,因为db请求本身是异步的

希望我能够做到这一点

1 个答案:

答案 0 :(得分: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`
  });
}
相关问题