嵌套函数的回调

时间:2016-05-26 03:46:44

标签: javascript

我有这样的功能:

//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,'第一个函数的成功')。如何将这些消息返回给任何调用它们的消息,以便它们知道是否有任何错误或者它是否成功完成了第3个函数?

1 个答案:

答案 0 :(得分:1)

你正在做正确的事!当您在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
                   }
               });
          }
  });

});