NodeJs:等待ForEach函数
NodeJs: Wait for ForEach function
我编写了一个验证函数,用于检查数组是否有效。我想返回多个错误。我搜索了那个主题,但无法用promise、异步模块运行它。我是NodeJS的新手,如果你能帮助我,我将不胜感激。
function validateNewResultUnits(sets, req) {
var validate = [];
sets.forEach(function(setItem) {
setItem.forEach(function(item) {
if (item.hasOwnProperty("name") == false) {
validate.push({
'name': 'Name has to be set'
});
} else {
if (item.name === "" || item.name === null || item.name === undefined) {
validate.push({
'name': 'Name cannot be empty'
});
} else {
Exercise.forge({
name: req.body.name
}).fetch({
withRelated: [{
'resultUnits': function(qb) {
qb.where('name', item.name);
}
}]
}).then(function(exercise) {
console.log("Länge:" + exercise.related('resultUnits').length);
if (exercise.related('resultUnits').length === 0)
validate.push({
'name': 'ResultUnit not found'
});
}).catch(function(error) {
validate.push({
'name': 'An Error occured'
});
});
}
}
if (item.hasOwnProperty("value") == false) {
validate.push({
'value': 'Value has to be set'
});
} else {
if (item.value === "" || item.value === null || item.value === undefined) {
validate.push({
'value': 'Name cannot be empty'
});
} else {
if (isNaN(item.value)) validate.push({
'value': 'Value has to be number'
});
}
}
});
});
return validate;
}
var validate = validateNewResultUnits(req.body.sets, req);
console.log(validate);
if (validate.length == 0) {
// ...
}
在函数准备返回某些内容之前,console.log(validate);
返回undefined。非常感谢。
编辑:承诺尝试(在第二秒内)
var promise = new Promise(function(resolve) {
Exercise.forge({name: req.body.name })
.fetch({
withRelated: [{'resultUnits': function(qb) {
qb.where('name',item.name)
}}]
}).then(function(exercise) {
console.log("Länge:"+exercise.related('resultUnits').length);
if (exercise.related('resultUnits').length === 0)
resolve({'name':'ResultUnit not found'});
}).catch(function(error) { resolve({'name': 'An Error occured'}); });
});
promise.then(function(result) {
validate.push(result);
});
问题出现在Exercise.forge({name: req.body.name }).fetch(...)
中,因为它异步运行,这使得validateNewResultUnits
函数继续执行,直到返回未定义的结果。
我建议您更改代码以包含promise,而不是那些丑陋的异步回调,这将需要更改validateNewResultUnits
函数本身及其任何调用方。以下是一些可以帮助您快速理解承诺的资源:
https://strongloop.com/strongblog/promises-in-node-js-with-q-an-alternative-to-callbacks/
理解node.js 中的承诺
http://howtonode.org/promises
https://vimeo.com/144550711
https://vimeo.com/144550811
https://vimeo.com/144550913
编辑
这是提供的代码的副本,但使用promise代替
function validateNewResultUnits(sets, req) {
return new Promise(function(resolve, reject){
var validate = [];
var internalPromises = [];
sets.forEach(function(setItem) {
setItem.forEach(function(item) {
if (item.hasOwnProperty("name") == false) {
validate.push({'name': 'Name has to be set'});
} else {
if (item.name === "" || item.name === null || item.name === undefined) {
validate.push({'name': 'Name cannot be empty'});
} else {
var internalPromise = Exercise.forge({name: req.body.name}).fetch({
withRelated: [{
'resultUnits': function (qb) {
qb.where('name', item.name);
}
}]
});
internalPromise.then(function(exercise) {
console.log("Länge:" + exercise.related('resultUnits').length);
if (exercise.related('resultUnits').length === 0)
validate.push({'name': 'ResultUnit not found'});
}).catch(function(error) {
validate.push({'name': 'An Error occured'});
});
internalPromises.push(internalPromise);
}
}
if (item.hasOwnProperty("value") == false) {
validate.push({'value': 'Value has to be set'});
} else {
if (item.value === "" || item.value === null || item.value === undefined) {
validate.push({'value': 'Name cannot be empty'});
} else {
if (isNaN(item.value))
validate.push({'value': 'Value has to be number'});
}
}
});
});
if(internalPromises && internalPromises.length) {
Promise.all(internalPromises).then(function (value) {
console.log(value);
resolve(validate);
}, function (reason) {
console.log(reason);
resolve(validate);
});
} else {
resolve(validate);
}
});
}
var validatePromise = validateNewResultUnits(req.body.sets, req);
validatePromise.then(function(result){
console.log(result);
if (result.length == 0) {
// ...
}
});
相关文章:
- ko.com在foreach$data变量上添加了write函数
- 使用jQuery来foreach iframe-src,并通过函数获取ID和操作
- 从jquery foreach内部中断函数
- 将参数传递给 Array.forEach 回调函数
- 得到"TypeError:对象不是函数“”;在forEach循环中使用超级测试/超级代理时
- MongoDB map/reduce,forEach不是一个函数
- 如何使用forEach函数推送变量中的值
- Wordpress:Jquery.html函数现在在PHP foreach循环中执行
- angular.forEach,可以使用函数(键)作为范围扩大
- forEach的奇怪数组构造函数行为
- foreach循环等待,直到每个步骤中的每个函数都完成
- 不清楚从函数内的 javascript forEach 循环返回
- Unity javascript 中的 Foreach 等效函数
- Knockout.js:在原型上调用函数,但保留在foreach的上下文中
- 在forEach中调用类函数:Javascript如何处理“this”关键字
- 匿名回调函数抛出错误,使一个像forEach一样遍历数组
- 如何将 JavaScript forEach 循环/函数转换为 CoffeeScript
- 获取 Array.forEach 函数的返回值
- array.forEach之后的回调函数
- 在 razor foreach 语句中调用 JS 函数