如何在节点中休眠线程。不影响其他线程的js ?

时间:2021-07-30 20:40:40

As per Understanding the node.js event loop, node.js supports a single thread model. That means if I make multiple requests to a node.js server, it won't spawn a new thread for each request but will execute each request one by one. It means if I do the following for the first request in my node.js code, and meanwhile a new request comes in on node, the second request has to wait until the first request completes, including 5 second sleep time. Right?

根据对节点的理解。js事件循环,节点。js支持单个线程模型。这意味着如果我向一个节点发出多个请求。js服务器,它不会为每个请求生成一个新的线程,而是逐个执行每个请求。这意味着如果我对节点中的第一个请求执行以下操作。当一个新的请求进入节点时,第二个请求必须等到第一个请求完成,包括5秒的睡眠时间。对吧?

var sleep = require('sleep');
    sleep.sleep(5)//sleep for 5 seconds

Is there a way that node.js can spawn a new thread for each request so that the second request does not have to wait for the first request to complete, or can I call sleep on specific thread only?

是否有一个节点。js可以为每个请求生成一个新的线程,这样第二个请求就不必等待第一个请求完成,或者我可以只在特定的线程上调用sleep吗?

3 个解决方案

#1


100  

If you are referring to the npm module sleep, it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:

如果您指的是npm模块睡眠,它在readme中指出睡眠将阻止执行。所以你是对的——这不是你想要的。相反,您希望使用非阻塞的setTimeout。这是一个例子:

setTimeout(function() {
  console.log('hello world!');
}, 5000);

For anyone looking to do this using es7 async/await, this example should help:

对于任何希望使用es7 async/ wait进行此操作的人来说,这个示例应该有所帮助:

const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));

const example = async () => {
  console.log('About to snooze without halting the event loop...');
  await snooze(1000);
  console.log('done!');
};

example();

#2


1  

In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:

如果您在每个请求中都有一个包含异步请求的循环,并且希望在每个请求之间有一定的时间,您可以使用以下代码:

   var startTimeout = function(timeout, i){
        setTimeout(function() {
            myAsyncFunc(i).then(function(data){
                console.log(data);
            })
        }, timeout);
   }

   var myFunc = function(){
        timeout = 0;
        i = 0;
        while(i < 10){
            // By calling a function, the i-value is going to be 1.. 10 and not always 10
            startTimeout(timeout, i);
            // Increase timeout by 1 sec after each call
            timeout += 1000;
            i++;
        }
    }

This examples waits 1 second after each request before sending the next one.

这个示例在每个请求后等待1秒,然后发送下一个请求。

#3


0  

Please consider the deasync module, personally I don't like the Promise way to make all functions async, and keyword async/await anythere. And I think the official node.js should consider to expose the event loop API, this will solve the callback hell simply. Node.js is a framework not a language.

请考虑一下deasync模块,我个人不喜欢让所有的函数都异步,关键字async/ waiting。我认为是官方节点。js应该考虑公开事件循环API,这将简单地解决回调地狱。节点。js是框架而不是语言。

var node = require("deasync");
node.loop = node.runLoopOnce;

var done = 0;
// async call here
db.query("select * from ticket", (error, results, fields)=>{
    done = 1;
});

while (!done)
    node.loop();

// Now, here you go

#1


100  

If you are referring to the npm module sleep, it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:

如果您指的是npm模块睡眠,它在readme中指出睡眠将阻止执行。所以你是对的——这不是你想要的。相反,您希望使用非阻塞的setTimeout。这是一个例子:

setTimeout(function() {
  console.log('hello world!');
}, 5000);

For anyone looking to do this using es7 async/await, this example should help:

对于任何希望使用es7 async/ wait进行此操作的人来说,这个示例应该有所帮助:

const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));

const example = async () => {
  console.log('About to snooze without halting the event loop...');
  await snooze(1000);
  console.log('done!');
};

example();

#2


1  

In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:

如果您在每个请求中都有一个包含异步请求的循环,并且希望在每个请求之间有一定的时间,您可以使用以下代码:

   var startTimeout = function(timeout, i){
        setTimeout(function() {
            myAsyncFunc(i).then(function(data){
                console.log(data);
            })
        }, timeout);
   }

   var myFunc = function(){
        timeout = 0;
        i = 0;
        while(i < 10){
            // By calling a function, the i-value is going to be 1.. 10 and not always 10
            startTimeout(timeout, i);
            // Increase timeout by 1 sec after each call
            timeout += 1000;
            i++;
        }
    }

This examples waits 1 second after each request before sending the next one.

这个示例在每个请求后等待1秒,然后发送下一个请求。

#3


0  

Please consider the deasync module, personally I don't like the Promise way to make all functions async, and keyword async/await anythere. And I think the official node.js should consider to expose the event loop API, this will solve the callback hell simply. Node.js is a framework not a language.

请考虑一下deasync模块,我个人不喜欢让所有的函数都异步,关键字async/ waiting。我认为是官方节点。js应该考虑公开事件循环API,这将简单地解决回调地狱。节点。js是框架而不是语言。

var node = require("deasync");
node.loop = node.runLoopOnce;

var done = 0;
// async call here
db.query("select * from ticket", (error, results, fields)=>{
    done = 1;
});

while (!done)
    node.loop();

// Now, here you go