akxer
akxer

Reputation: 132

Pause a function to listen to requests

I am running a long loop inside a function in NodeJS and knowing that JS by its nature does not allow anything to interrupt a function, I wanted to know is their a way to pause a function's execution to listen to requests from client that I am no able to do currently

Upvotes: 0

Views: 414

Answers (2)

Lorenz Meyer
Lorenz Meyer

Reputation: 19915

You cannot interrupt a function while it is executing. What you need to do is refactoring the loop that causes problems.

You must break the loop itself:

  • Instead of a loop, each iteration should call the next using setTimeout()
  • Use a generator. Passing to and from a generator breaks the eventloop and allows other events executing in between.

This is what I mean by using setTimeout :

Given the function :

function syncLoop(args) {
    var localVar;
    for (i = 0; i < max; i++) {
        doSomething(args, localVar) 
    } 
} 

Replace the loop with setTimeout (or setImmediate()), like this :

function asyncLoop(args) {
    var localVar; 
    function innerLoop(i){ if(i < max){ 
         doSomething(args, localVar) 
         setTimeout(function(){
               i++; innerLoop(i); 
         }, 0);
     } } 
    innerLoop(0);
} 

This way, at each iteration, the control is passed to the event loop, and other independent requests can be served.

Upvotes: 1

Sergaros
Sergaros

Reputation: 831

There's not very good idea to stop requests handle. Try use promises, this is very rough example but you can understand base idea:

...
http.createServer(function(req, res) {
    let bigData = [];

    //parse your big data in bigData
    ...

    new Promise(function(resolve, reject){
        for(let i = 0; i < bigData.length; i++){
            //some long calculate process

            //if error
             return reject(error);

            //if all calculated
             return resolve(result);
        }
    })
    .then(function(result){
        res.end(result);
    }, function(function(error){
        throw error;
    });
});
...

Maybe try this:

let count = 0;
for(let i = 0; i < bigData.length; i++){

    /*something calculation
        ....
    */
    count++;

    //this code allow your server every 50 iterations "take a brake" and handle other requests
    if(count === 50){
        count = 0;
        setTimeout(()=>{ 
        }, 100);
    };

};

Upvotes: 0

Related Questions