循环阻塞。他们似乎对Node.JS的想法漠不关心。如何处理for
循环或while
循环似乎是最佳选择的流程。
例如,如果我想打印一个随机数最多为number * 1000
的表格,我会想要使用for
循环。在Node.JS中有没有一种特殊的方法来处理它?
答案 0 :(得分:3)
循环本身并不坏,但这取决于具体情况。在大多数情况下,您需要在循环内部执行一些异步操作。
所以我个人的偏好是根本不使用循环,而是使用功能对应物(forEach / map / reduce / filter)。这样我的代码库保持一致(如果需要,同步循环很容易变为异步循环)。
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));
}
请注意,您可以轻松地在同步和异步版本之间进行更改,结构几乎保持不变。
希望这有点帮助。
答案 1 :(得分:-1)
如果你正在对内存中的数据进行循环(例如,你想要通过一个数组并为所有对象添加一个prop),循环将正常工作,但是如果你需要在循环中做一些事情,比如保存值对于数据库,你会遇到一些问题。
我意识到这不是答案,但这是一个可以帮助某人的建议。我发现处理这个问题最简单的方法之一是使用速率限制器和forEach(我不喜欢真正的承诺)。这也带来了额外的好处,可以选择并行处理事物,但只有在完成所有事情后继续: 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();
}
});
});
});
};