简体   繁体   中英

Pause a function to listen to requests

我在NodeJS中的函数内部运行了一个长循环,并且知道JS本质上不允许任何中断该函数,所以我想知道这是他们暂停函数执行以侦听来自客户端的请求的一种方法目前能够做

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.

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);
    };

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM