[英]Writing nested non-blocking loops in node.js
How to properly write the following set of loops in Node.Js without blocking the event loop or without causing out of memory error. 如何在Node.Js中正确编写以下循环集而不阻塞事件循环或不引起内存不足错误。
What I have tried so far includes 到目前为止,我尝试过的内容包括
The code. 编码。
for(var i = 0; i < 2000; i++)
for(var j = 0; i < 2000; j++)
for(var k = 0; k < 2000; k++)
console.log(i + ":" + j + ":" + k);
Also created a JSFiddle to play around here 还创建了一个JSFiddle在这里玩
Not really sure what your use-case is. 不太确定您的用例是什么。 Javascript is blocking as it's single threaded, it would have to run the loop before moving to something else.
Javascript正在阻塞,因为它是单线程的,因此必须先运行循环,然后再转移到其他地方。
You could for example use a generator to run each iteration on an event though. 例如,您可以使用生成器在事件上运行每个迭代。
function* ticker() {
for(let i = 0; i < 10; i++)
for(let j = 0; i < 10; j++)
for(let k = 0; k < 10; k++)
yield[i, j, k];
}
const gen = ticker();
setInterval(() => console.log(gen.next().value), 500);
console.log('I am at the end (called straight away)');
You need to combine setImmediate
/ setTimeout
/etc. 您需要结合使用
setImmediate
/ setTimeout
/ setImmediate
with the async.js library. 使用async.js库。
async.each
is only for orchestration, it doesn't provide any asynchrony itself. async.each
仅用于业务流程,它本身不提供任何异步。
function getPerm(reducedWordList, callback) {
var sevenLtrWords = _.filter(reducedWordList, word => word.length == 7);
var fourLtrWords = _.filter(reducedWordList, word => word.length == 4);
async.each(sevenLtrWords, (i, cb) => {
async.each(sevenLtrWords, (j, cb) => {
async.each(fourLtrWords, (k, cb) => {
console.log(i + " " + j + " " + k);
setTimeout(cb, 0);
}, cb);
}, cb);
}, callback);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.