如何睡在node.js的线程不影响其他线程? [英] How to sleep the thread in node.js without affecting other threads?

查看:208
本文介绍了如何睡在node.js的线程不影响其他线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据理解Node.js的事件循环,Node.js的支持单线程模型。这意味着,如果我做多次请求到服务器的nod​​e.js,它不会产卵每个请求一个新的线程,但将由一个执行每个请求之一。这意味着,如果我做我的node.js code中的第一个请求以下,同时新的请求到来时节点上,第二个请求必须等待,直到第一个请求完成,其中包括5秒的睡眠时间。对吧?

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?

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

有没有一种方式,可以的Node.js产卵为每个请求一个新的线程,使得第二请求没有等待完成第一个请求,或者我可以调用特定的线程睡眠而已?

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?

推荐答案

如果你指的是故宫模块睡眠,它在睡眠自述笔记将阻止执行。那么,你是正确的 - 这是不是你想要的。相反,你要使用的setTimeout 这是非阻塞。下面是一个例子:

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:

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

这篇关于如何睡在node.js的线程不影响其他线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆