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)");14 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.
1Why 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. });