How does a child function prevent subsequent execution in the parent function?
1. The commonly used method is: return a variable in the parent function based on what the child function gets, and use the variable to determine whether to return the parent function in the parent function.
function parent(){
console.log(1)
const res = children()
if(res) return
console.log(2)
//...
}
function children(){
//...
console.log(3)
return true //false
}
parent()
//1
//3
no print 2
2. Unconventional method: Use throw error and try...catch to avoid executing the subsequent logic.
function parent(){
console.log(1)
const res = children()
console.log(2)
//...
}
function children(){
//...
console.log(3)
throw Error(true)
//false
}
try{
parent()
} catch(e){
console.log(e)
}
console.log(4)
/**
1
3
Error: true
at children (<anonymous>:11:9)
at parent (<anonymous>:3:15)
at <anonymous>:15:3
4
*/
no print 2