gpt4 book ai didi

javascript - 如何处理异步ajax响应

转载 作者:行者123 更新时间:2023-12-02 14:03:52 25 4
gpt4 key购买 nike

我想从我的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com