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
}
});
asked Oct 22, 2014 at 9:18
vidulaJ
1,2701 gold badge16 silver badges31 bronze badges
1 Answer 1
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
vidulaJ
Thanx Villiam. I'd go with this & try this.
Explore related questions
See similar questions with these tags.
lang-js
callbackis a parameter toloadXML()and isn't passed anywhere else. Did you tryconsole.log(arguments);inside the function?