我有多个任务函数调用 validate(),如果存在验证错误,它们需要返回/转义主函数。是否可以使用 typescript/javascript 执行类似的操作? (我在 Node 环境中工作)
cont validate = () => {
//validation etc...
//if validation error
// return & request mainFunction() to also return
}
const taskOne = () => {
validate() //some validation error happened when this got called..
}
const taskTwo = () => {
validate()
}
const mainFunction = () => {
taskOne();
taskTwo(); //will not run because taskOne requested return
}
mainFunction();
我希望避免在执行每个任务后创建 if 检查,以防我想通过更多任务调用验证函数来扩展我的代码。我怎样才能完成这个任务?
最佳答案
您可以返回一个 bool 值并链接验证。
const validate = (prop) => {
// validation etc...
// if validation error
// return false & request mainFunction() to also return
return true;
}
const taskOne = () => validate(one);
const taskTwo = () => validate(two);
const mainFunction = () => taskOne() && taskTwo() && taskThree() /* && ... */;
mainFunction();
关于javascript - 从另一个函数转义/返回一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44613659/