Hello I am currently executing a child function from a parent However if something particular happens I want the child function to stop the rest of the parent function to stop executing
How do I do this without using a return ?
The child function is a module
Main.js
console.log("Beginning")
const func_import = require("/module.js")
func_import()
console.log("not to be executed in certain cases")
module.js
module.exports = async() => {
console.log("something")
}
I tried to use a simple return value However this just returned an undefined even after I used await
It's possible, but very, very strange. You can throw an error in the child:
module.exports = () => {
if (condition) {
throw new Error();
}
}
This will cause the parent (and each of its parents) to stop executing at the point of the function:
console.log("Beginning")
const func_import = require("/module.js")
func_import() // <-- stops here
console.log("not to be executed in certain cases")
Don't do this. Errors should be used for exceptional circumstances (there's a reason they're called "exceptions"), not for simple control flow. Return a value instead.
module.exports = () => {
// other code
return condition;
}
console.log("Beginning")
const func_import = require("/module.js")
const condition = func_import();
if (!condition) {
console.log("not to be executed in certain cases")
}