【问题标题】:How to handle an ajax response which is asynchronous如何处理异步的ajax响应
【发布时间】:2016-10-23 16:26:21
【问题描述】:

我想在 nodejs 中从我的数据库中检索一些数据。 检索这些数据是异步请求,我们也是 ajax 请求。

客户端.js

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

});

服务器.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 请求本身是异步的

希望我能说清楚

【问题讨论】:

    标签: javascript jquery ajax node.js asynchronous


    【解决方案1】:

    您正在调用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`
      });
    }
    

    【讨论】:

    • 哦,我觉得垃圾^^
    • @xhallix:我们都去过那里。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2023-02-02
    • 2017-06-10
    • 1970-01-01
    相关资源
    最近更新 更多