I write a validate function where I want to check if a array is valid to be instert. I want to return multiple errors. I searched for that topic but couldnt get it runnig with promises, async-module. Im very new to NodeJS and would be very grateful if you could help me.
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) {
// ...
}
The console.log(validate);
return undefined before the function is ready to return something.
Thanks a lot.
EDIT: Promise Attempt (inside the second forEach)
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);
});