Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
henriquegiuliani
12,296 PointsWhy my callback isn't running?
I'm trying to understand callbacks in JavaScript but i don't know why isn't running...
Here's the code:
function sum(n1, n2, callback){
return n1 + n2;
}
sum(4,5,function(){
console.log("Result: " + this);
});
console.log("processing ...");
It doesn't display the result when i run the script... it should appeear "processing..." first and then the result.
2 Answers
Bryan Peters
11,996 PointsWhen you use a callback pattern, you don't use the return. Your callback function should receive the value as a parameter. Try this - it uses the callback if provided, otherwise it returns the value normally.
function sum(n1, n2, callback) {
var result = n1 + n2;
if (callback) {
callback(result);
} else {
return result;
}
}
sum(4,5,function(val){
console.log("Result: " + val);
});
console.log("processing ...");
Note: There are other use cases for callbacks that don't return a value, in that case you would just call callback() in your function, and the callback function would not have a parameter. Example:
function startProcess(callback) {
console.log("process started");
//do stuff
callback()
}
function processDone(){
console.log("process done");
}
startProcess(processDone);
henriquegiuliani
12,296 PointsHm, thanks a lot!! Much clearer now hehe
henriquegiuliani
12,296 Pointshenriquegiuliani
12,296 Pointsthanks for the answer... but what does it mean "if(callback)" ???
Bryan Peters
11,996 PointsBryan Peters
11,996 Pointsif (callback) checks to see if a callback function was received. If it was, it sends the value via the callback, otherwise it sends the value back via return.
so you could do: