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 trialGeorge Roberts
Full Stack JavaScript Techdegree Student 8,474 PointsIf callbacks only run once the parent completes, why do statements coming after a callback in a parent's body still run?
Hi, when add is called below, the callback executes and then 'still running' is logged to the console. I don't understand how that can be if callbacks only run once the parent has completed. In this case it seems the parent is still running otherwise 'still running' would not be logged after the sum of 2 + 4 is logged? Thanks
function add(a, b, callback) {
callback(a + b);
console.log("still running");
}
add(2, 4, function(sum) {
console.log(sum);
});
// first logs 6 (callback executes)
// then logs 'still running' (2nd statement in the parent function)
1 Answer
Steven Parker
231,268 PointsThe notion that "callbacks only run once the parent has completed" isn't correct. There are certainly some cases in asynchronous programming where they do happen to run after the parent has completed, but they don't only work that way.
In this particular code the callback is synchronous, so it runs first and then control returns to the parent.
George Roberts
Full Stack JavaScript Techdegree Student 8,474 PointsGeorge Roberts
Full Stack JavaScript Techdegree Student 8,474 PointsThanks for clearing that up for me!