Monday, 5 September 2016

javascript: pass return value in callback function



Please help me understand this:




I have an object self.domainSettings() which has a save method. The save returns the result which I want to use in callback function to populate success or error message. I am using following code:



self.domainSettings().save(function(data){
console.log('in here');
console.log(data);
console.log('outta here');
}());

function save(){
return 'success';

};


When I do console.log(data) is it guaranteed that the save has finished executing ? Also it says data is undefined because the return value of save is not getting passed to callback function I guess. How do I get that ?


Answer



You have to pass callback in save() in order to access the result from a callback.



function save(fn){
return fn('success');
};


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...