首页 > nodejs两个异步请求返回值错位?

nodejs两个异步请求返回值错位?

现在有一台nodejs运行 着一个http服务
现在有A用户发送了请求A到 服务器,node需要调用另外一个服务去取数,此时还没有取到数,等待回调触发 完成取数事件,
这时候B用户发送了请求B到服务器,node调用服务去取数,然后B已经取到数了,进入了callback,但是此时A的callback还没有触发,导致B用户的请求结果被返回了A用户。这是为什么呢

function onRequest(req, res) {    
    var postData = "";   
    var pathname = url.parse(req.url).pathname;    
    
    req.setEncoding("utf8");    
    req.addListener("data", function(postDataChunk) {      
        postData += postDataChunk;      
        console.log("Received POST data chunk '" +  postDataChunk + "'.");    
    });    
    req.addListener("end", function() {      
        if (pathname.indexOf('/whywhy') > -1) {
            //发送请求
            sendRequestToOtherService(pathname);
            //有没有可能问题出在once这里
            OtherService.once('complete',function(msg) {
                var sendData = JSON.stringify(msg.iteminfo);
                res.writeHead(200, {"Content-Type": "text/plain"});
                res.end(sendData); 
            });
                
        } else {
            logwarn.info("Request for " + pathname );    
            res.setHeader('Content-Type', 'text/html');
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end();
        }
    });  
} 
http.createServer(onRequest).listen(8081);

你的怀疑是有可能的,为什么不测试一下呢。

【热门文章】
【热门文章】