![](/img/trans.png)
[英]Why does my .catch() function not return the error name in a promise?
[英]Why does my function not return the error string?
我下面有功能。 它會執行所需的操作,只是它不會返回我想要的錯誤字符串。
它總是返回“”。
我已經設置了斷點,並看到它進入了每個錯誤情況,但是它並沒有返回到那里。 它在函數末尾返回。
我迷路了,我確定自己犯了一個非常愚蠢的錯誤,但我不明白...
請救我幾根頭發:)
public validatePanel = () => {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
return "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
return "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
return "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
return "Please select a value for your filter";
}
});
}
});
return "";
}
正如Alex Bykov指出的那樣,您的forEach
函數不會引起返回。
關於MDN的問題
函數的返回值不確定
返回
值未定義。
這意味着您無能為力將生成可以使用的返回值。 同樣,根據MDN,除了引發異常之外,沒有其他方法可以停止或中斷循環。
除了拋出異常外,沒有其他方法可以停止或中斷forEach()循環。 如果您需要這種行為,則forEach()方法是錯誤的工具,請改用普通循環。 如果要為謂詞測試數組元素並且需要布爾返回值,則可以改用every()或some()。 如果可用,新方法find()或findIndex()還可用於在真謂詞上提前終止。
這意味着您將需要在forEach
循環中引發異常,然后捕獲該異常並返回如下所示的字符串( 除非您使用常規的for循環,否則您可以執行任何操作 )
try {
this.Queries().forEach(function(q, i) {
if(q.from() == "" || q.from() == null || q.from() == undefined) {
throw "Please select a database";
}
if(q.select().length > 0) {
q.select().forEach(function(s, j) {
if(s.selectoption() == "" || s.selectoption() == null || s.selectoption() == undefined){
throw "Please select a stat to show";
}
});
}
if(q.where().length > 0) {
q.where().forEach(function(w, j) {
if(w.whereoption() == "" || w.whereoption() == null || w.whereoption() == undefined){
throw "Please select a filter to filter on";
}
if(w.wherevalue() == "" || w.wherevalue() == null || w.wherevalue() == undefined) {
throw "Please select a value for your filter";
}
});
}
});
}
catch(err) {
console.log(error);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.