I am using step library for synchronous behavior for validating and saving contacts,
Following are the code which i am using right now
exports.actions = function(req, res, ss) {
var Step= require('step');
req.use('session');
return {
addCon:function(contactObject){
Step(
function validation(){
var accounts =contactObject.contacts.accounts;
accounts.forEach(function(){
//database call
services.user.get(updateObj,function(err,rec){
if(err || rec == null)
{
res("Saving Contact Failed,user Does Not Exist");
//here responding to client for showing alert message
return false;
}
if(userId === rec.friendId){
res("Error");
//here responding to client for showing alert message
return false;
}
});
});
},
function saving(){
//saving
}
,
function pusblishing tofriend(){
//stuff
}
)
}
}
}
Actually i want to skip the saving function if any error occurs in the validation function. and any idea tobreak the loop, return false is not working.
I'm not 100% on step but it appears you can pass it this
as a callback function which will give you the ability to pass on errors and then to throw errors (as in the documentation).
The problem you have is you're returning in the functions of the loop so it will end that function and not the bigger Step
function. You're better off passing a this
function in the end of one of the functions like this, and doing the error checking later:
Step(
function hello() {
console.log('Hello');
this(err, 'Hello');
},
function howareyou (err, greeting) {
if (err) return something ...
Step will stop when you return in on one of the main functions it is trying to step through.
However, it looks for your use case, it would be better to use the async library's waterfall which has something similar to what you're describing built in AND you can handle errors in a single error function in the end.