我有一个这样的函数:
//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 }
});
}
});
});
然后我调用这个函数,如下所示:
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 );}
});
我很困惑在嵌套函数中将回调放在哪里。例如,如果我没有任何嵌套函数,我只需在正文中返回回调(null,'第一个函数成功')。我怎样才能将这些消息返回给调用它们的任何地方,以便他们知道是否存在任何错误或者是否成功一直到达第三个函数?
最佳答案
你做的一切都是对的!您可以在每次错误时在 myFirstFunction 中传递回调时调用回调,即
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
}
});
}
});
});
关于javascript - 嵌套函数的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37451218/