Node.JS应该避免循环,还是有特殊的方法来处理它们?

循环阻塞。 他们似乎无视Node.JS的想法。 如何处理for循环或while循环似乎是最好的select。

例如,如果我想打印一个随机数number * 1000的表格,我想使用for循环。 有没有一种特殊的方式来处理Node.JS这个?

循环本身不是坏的,但取决于情况。 在大多数情况下,你将需要在循环内部做一些asynchronous的东西。

所以我个人的偏好是根本不使用循环,而是使用函数对应(for each / map / reduce / filter)。 这样我的代码库保持一致(如果需要,同步循环很容易变成asynchronous)。

 const myArr = [1, 2, 3]; // sync loops myArr.forEach(syncLogFunction); console.log('after sync loop'); function syncLogFunction(entry) { console.log('sync loop', entry); } // now we want to change that into an async operation: Promise.all(myArr.map(asyncLogFunction)) .then(() => console.log('after async loop')); function asyncLogFunction(entry) { console.log('async loop', entry); return new Promise(resolve => setTimeout(resolve, 100)); } 

请注意,在同步和asynchronous版本之间切换的方式很简单,结构几乎相同。

希望这个对你有帮助。

如果你正在内存中的数据循环(例如,你想要通过一个数组,并添加一个道具所有对象),循环将正常工作,但如果你需要在循环内做一些事情,如保存到数据库的值,你会遇到一些问题。

我意识到这不完全是答案,但这是一个可以帮助别人的build议。 我发现处理这个问题最简单的方法之一是使用率限制器forEach(我不喜欢真正的承诺)。 这也提供了额外的好处,可以select并行处理,但只有在完成所有工作时才能继续: https : //github.com/jhurliman/node-rate-limiter

 var RateLimiter = require('limiter').RateLimiter; var limiter = new RateLimiter(1, 5); exports.saveFile = function (myArray, next) { var completed = 0; var totalFiles = myArray.length; myArray.forEach(function (item) { limiter.removeTokens(1, function () { //call some async function saveAndLog(item, function (err, result) { //check for errors completed++; if (completed == totalFiles) { //call next function exports.process(); } }); }); }); };