我在下面提到的函数中使用了两个 return 语句。但仍然是所有用户的函数循环。
module.exports.getByKey = function(key, callback) {
User.find().populate('licences').exec(function(err, users) {
if(err) {
return callback(err);
}
var keyFound = false;
users.forEach(function(user) {
console.log("user found " + user.name);
user.licences.forEach(function(licence) {
console.log("licence found");
if(licence.key == key) {
keyFound = true;
callback(null, user);
return;
}
}, this);
if(keyFound) {
console.log("+++++++++++++++++++++++");
return;
}
}, this);
// return callback({error: "Invalid Key"});
});
}
最佳答案
Array#forEach
迭代数组的所有元素,它不考虑任何返回值。
要使用短路,您可以使用 Array#some
并返回 true
以停止迭代或 Array#every
,这里需要返回一个真值来继续循环。
通过使用嵌套方法,您需要将返回值冒泡到外部数组循环。
var keyFound = users.some(function(user) { // return some
return user.licences.some(function(licence) { // return some
if (licence.key == key) {
callback(null, user);
return true;
}
}, this);
}, this);
关于javascript - 为什么这段代码不会破坏嵌套的 forEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46373392/