I have a function such as this:
//parent function
function myFirstFunction(param1, callback) {
//outside inside
mySecondFunction(param1,function(error,result){
if(error){ //should return 'error in mySecondFunction' to whoever called this }
else{
myThirdFunction(error2,result2){
if(error2){ //should return 'error in myThirdFunction' to whoever called this }
else{ //should return 'Success in myThirdFunction' to whoever called this }
});
}
});
});
I then call this function such as this:
myFirstfunction(p1, function(e,r){
if(e){ console.log('The error returned is : ' + e) };
else{console.log('Success! The message returned should be Success in myThirdFunction. Is it? ' + r );}
});
I am confused where to put the callbacks inside of nested functions. For instance if I didn't have any nested functions I would simply return callback(null, 'Success in first function') in the body. How can I return these messages back to whatever called them so they know if there were any errors or if it made it all the way to the 3rd function successfully?
asked May 26, 2016 at 3:46
user2924127
6,27218 gold badges88 silver badges147 bronze badges
1 Answer 1
You're doing everything right! You can just call the callback as you passed it in myFirstFunction with each error i.e.
function myFirstFunction(param1, callback) {
//outside inside
mySecondFunction(param1,function(error,result){
if(error){
callback("error in mySecondFunction");
}
else{
myThirdFunction(error2,result2){
if(error2){
callback("error in myThirdFunction");
}
else{
callback(null,result2);//I'm not sure what data you want here
}
});
}
});
});
answered May 26, 2016 at 3:58
Joe Thomas
6,5376 gold badges29 silver badges38 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js