1

Say I have a function like the following.

loadXML('Method', requestString, function(callback){
   // The function as a callback parameter to loadXML goes here.

   // Here I am calling the callback function like this       
   if(callback != null){
       callback();
   }
});

But I want to define this callback function inside the loadXML function. So can I do this as following?

loadXML('Method', requestString, function(callback){
   // The function as a callback parameter to loadXML goes here.

   // Here I have to call the callback function like this, (do I?) which is a 
   // callback parameter to callback function of loadXML
   callback = function(){
       // The callback function implementation goes here
   }
});
6
  • I think that the callback is a parameter to loadXML() and isn't passed anywhere else. Did you try console.log(arguments); inside the function? Commented Oct 22, 2014 at 9:22
  • 1
    Why would you define a function and then not use it? And if you aren't passing it into the function, it isn't really a callback anyway. What are you actually trying to achieve? Commented Oct 22, 2014 at 9:28
  • There is also a callback function for loadXML() which is defined there and I want to have another callback function to that function. Let me update the code then. Commented Oct 22, 2014 at 9:28
  • "Here I have to call the callback function like this" — That overwrites the callback function with a new function and doesn't call it at all. What are you trying to achieve? Commented Oct 22, 2014 at 9:36
  • I am trying to implement a callback function to a callback function inside the former callback function. I just want to know whether I am doing it right or what the right method is? Commented Oct 22, 2014 at 9:39

1 Answer 1

3

Maybe this could help you to understand the nested callbacks mechanism:

var loadXML;
var outerCB;
var innerCB;     

loadXML = function(method, requestString, cb) {
  // pass the innerCB implementation as argument to the outer cb
  if('undefined' !== typeof innerCB) {
    cb(innerCB);
  } else {
    // in case innerCB would not be defined
    cb(function() {
      console.log('hi from anonymous cb')
    });
  }
};


innerCB = function() {
  console.log('hi from innerCB cb!')
};

outerCB = function(callback) {
  if('undefined' !== typeof callback) {
    callback(); // innerCB();    
  } else {
    console.log('no cb passed, do something else')
  }    
}

loadXML('Method', 'abcd', outerCB) // hi from innerCB cb! 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanx Villiam. I'd go with this & try this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.