Node.js 中的长循环:使用定时器产生收益? [英] Long Loops in Node.js: Yielding Using Timers?
问题描述
我正在使用 Node.js 来循环最终可能是一个漂亮的大数组 个帖子.
I'm using Node.js to loop through what could eventually be a pretty big array of posts.
如果我使用客户端 JavaScript 做类似的事情,我会使用计时器 如此处所述 以免阻塞线程.
If I were doing something similar using client side JavaScript, I would use timers as explained here so as not to block the thread.
我的问题是:仍然是一个健全的练习服务器端吗?"或我应该以不同的方式解决问题吗?"
My Question is: "Is still a sound practice server side?" or "Should I approach the problem differently?"
推荐答案
在 node.js 中做到这一点的正确方法是将您的工作分解成块并使用 process.nextTick
在当前块完成后将下一个块排队.这样你就允许在每个工作块之间执行其他排队的回调.
The proper way to do that in node.js is to break up your work into chunks and use process.nextTick
to queue the next chunk once the current one has completed. That way you allow other queued callbacks to be executed between each chunk of work.
更新:从 Node.js 0.10 开始,setImmediate为此,通常应该使用
而不是 process.nextTick
,因为 setImmediate
会产生事件循环以确保 I/O 不被饿了,但 process.nextTick
没有.
UPDATE: as of Node.js 0.10, setImmediate
should typically be used instead of process.nextTick
for this purpose as setImmediate
yields to the event loop to make sure I/O is not being starved, but process.nextTick
doesn't.
这篇关于Node.js 中的长循环:使用定时器产生收益?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!