我想从我的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 请求中的 aync 服务器请求?
我认为这将类似于 promise
。
但是我怎样才能将它传递回我的ajax请求,因为数据库请求本身是异步的
希望我能够说清楚
最佳答案
您调用从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`
});
}
关于javascript - 如何处理异步ajax响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40205104/