2017-06-18 40 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();