Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Asynchronous Programming with JavaScript Asynchronous JavaScript with Callbacks Callbacks Review

George Roberts
seal-mask
.a{fill-rule:evenodd;}techdegree
George Roberts
Full Stack JavaScript Techdegree Student 8,474 Points

If 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
Steven Parker
210,867 Points

The 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.