Monday, 3 April 2017

How to write non-blocking async function in Express request handler

All:

I am pretty new to Node async programming, I wonder how can I write some Express request handler which can handle time consuming heavy calculation task without block Express handling following request?

I thought setTimeout can do that to put the job in a event loop, but it still block other requests:

var express = require('express');
var router = express.Router();


function heavy(callback){
    setTimeout(callback, 1);
}

router.get('/', function(req, res, next) {
    var callback = function(req, res){
        var loop = +req.query.loop;
        for(var i=0; i<loop; i++){
            for(var j=0; j<loop; j++){}
        }
        res.send("finished task: "+Date.now());
    }.bind(null, req, res);

    heavy(callback)
}); 

I guess I did not understand how setTimeout works(my understanding about setTimeout is after that 1ms delay it will fire up the callback in a seperated thread/process without blocking other call of heavy), could any one show me how to do this without blocking other request to heavy()?

Thanks



via Kuan

No comments:

Post a Comment