如何防止一个请求阻止其他请求?

时间:2015-06-25 02:23:44

标签: javascript node.js loops asynchronous

我一直在尝试创建一个方案,其中请求A将首先到达,但是处理需要很长时间,同时请求B将到达第二个,但是只需要几秒钟来处理,我希望请求B在请求A之前完成。但是,请求A当前不仅阻止自身,而且阻止请求B.

var http = require('http')
function block(){while(true){var x =2;}}
var server = http.createServer(function(req, res) {
if(req.url=='/wait'){block();}
  res.writeHead(200);
  res.end('Hello Http');
  console.log(req.url)
});
server.listen(3000);

2 个答案:

答案 0 :(得分:0)

如果你的最初目标是根据某些条件阻止请求,那么比使用while循环更好的方法。

虽然它会使你的代码异步,但这需要你稍微改变一下你的请求。

var server = http.createServer(function(req, res) {
    if (req.url == '/wait')
        setTimeout(serveRequest, 60000);
    else
        serveRequest();

    function serveRequest() {
        res.writeHead(200);
        res.end('Hello Http');
        console.log(req.url);
    }
});

答案 1 :(得分:0)

虽然请求a取决于请求b,但必须有一条规则来保证请求a1和b1是一对,而a2和b2是一对,依此类推。换句话说,它应该有一个检查算法两个请求是一对。

var em = new events.EventEmitter();
const EVENT_B_FINISH = 'bFinishedEvent';
var requestPairQueue = {};//key-value format,the key is the rid of request a,the value is the rid of request b.

//------request a arrive-----
var rid = //get the unique request id
//process a code......

if (requestPairQueue[rid]) {
   //the paired b request has processed,send a response directly
}
em.on(EVENT_B_FINISH,function() {
    if (requestPairQueue[rid]) {
       //the paired b request processed after a while,send a response
    }
});

//-----request b arrive----
var ridA = //the relation a request rid
var ridB = //the current b request id
//after process code....
requestPairQueue[ridA] = ridB; 
em.emit(EVENT_B_FINISH);