2017-06-18 68 views
0

我有多个任务函数调用validate(),如果有验证错误,需要返回/转义主函数。是否有可能用typecript/javascript做这样的事情? (我在一个节点的环境中工作)Escape /从另一个函数返回函数

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(); 

我想避免每个任务的情况下,执行后,我想扩大我的代码有更多的任务调用验证函数创建一个如果检查。我怎样才能完成这项任务?

+1

在验证失败时抛出错误并捕获它们? – Saravana

+0

我不希望应用程序停止,因为它是一个持续的观察者,验证应拒绝并创建一个错误的文件。相反,我希望它在用户触发文件上的保存事件后重新启动mainFunction来继续。 – Jonathan002

+0

您需要提供更多的上下文。你对返回的值做什么?最好是一些工作代码。就目前来看,这似乎不是一个好问题。 – Rick

回答

1

您可以返回一个布尔值并链接验证。

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(); 
+0

感谢您的回答。我不能在我的代码中使用它,因为我在分配变量并在特定任务中重用它们。例如让taskOne = taskOne();让taskTwo = taskTwo(taskOne); – Jonathan002

+2

也许你增加了一个例子,你喜欢做什么,返回值以及它们是如何连接的增量检查。 –

0

您可以使用简单的try/catch块,并在验证失败时使验证函数引发错误。

const validate =() => { 
    if(validationSucceeds) { 
    return true; 
    } else { 
    throw 'error message'; 
    } 
} 

const taskOne =() => { 
    validate() //some validation error happened when this got called.. 
} 

const taskTwo =() => { 
    validate() 
} 

const mainFunction =() => { 
    try { 
     taskOne(); 
     taskTwo(); //will not run because taskOne requested return 
    } catch(err) { 
     console.error(err); 
     return; 
    } 
} 

mainFunction();