Is there a way I can exit a parent function whilst inside that parent's child function?

Is there a way I can exit a parent function whilst inside that parent's child function? Sort of like how a child loop can escape it's parent loop with the break keyword suffixed with the name of the parent loop like parent: loop.

function parent() { function child() { return child; } child() console.log("I don't want this code to be run") } parent(); console.log("Just printing this means I escaped parent function (from child function)");
1

4 Answers

You can make it with an if statement. If the return value of child is true, then parent function exits immediately

function parent() { function child() { return true //I want to exit parent function from here } if (child()) { return; } console.log("still inside parent") } parent(); console.log("outside parent");

You can do something like that:

function parent() { quit = false function child() { quit = true return //I want to exit parent function from here } child() if (quit) { return } console.log("still inside parent") } parent(); console.log("outside parent");

Is there a way I can exit a parent function whilst inside that parent's child function?

No, you cannot force the parent function to return from a child function.

With that said, one way to solve this is by returning a value from child() that parent() can use:

function parent() { function child() { return true; } if(child()) console.log("still inside parent") } 

This is just like how any two functions interact even if they aren't nested.

1

Why not using Callback function as child?

function parent(child) { // Do parent stuff return child() console.log("You'll never reach here.") } // Call the parent and do the parent stuff first. parent(function() { // Do child stuff. return }) console.log("You'll be here after running parent followed by child."); 

Use the Promise approach:

function parent() { return new Promise( (resolve, reject) => { try { // Do parent stuff. resolve(function() { // Do child stuff. return true }) } catch (error) { return reject(error) } }); // You'll never reach here. } // Call the parent. parent() .then((isChildDone) => { if (isChildDone) { console.log("You'll be here after running parent followed by child."); } }) .catch((error) => { // Handle error if child hit error. }); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like