Well, you can use promises without reject.
(好吧,您可以使用承诺而不会拒绝。)
However you must be sure that resolve is called in all your function flows to trigger the "then" handler (or the function must end with an error or exception to trigger the catch clause). (但是,您必须确保在所有函数流中都调用resolve来触发“ then”处理程序(或者函数必须以错误或异常结尾才能触发catch子句)。)
Reject is often used to trigger error handling logic linked to variable values and results. (拒绝通常用于触发链接到变量值和结果的错误处理逻辑。)
If the only way your code would fail is due to an exception, then reject is not necessary (this is my opinion though) (如果您的代码失败的唯一方法是由于异常,那么拒绝是没有必要的(尽管这是我的观点))
As @Jared Smith pointed out, you should do things this way, where the promise actually can reject:
(正如@Jared Smith指出的那样,您应该以这种方式进行操作,在诺言实际上可以拒绝的地方:)
function isUserInDatabase(serverID, playerID) {
const query = "SELECT * FROM playerdata where serverID=" + serverID + " AND playerID=" + playerID;
return executeQuery(query).then(res => {
const isUndefined = res[0] === undefined
return !isUndefined
}).catch (e => {
console.error(e);
console.log("Error retrieving data from database.");
});
}
Though you will not be able to handle this promise errors (there's already a catch clause)
(尽管您将无法处理该promise错误(已经有一个catch子句))
You could ignore said catch clause and handle errors after calling isUserInDatabase:
(您可以在调用isUserInDatabase之后忽略上述catch子句并处理错误:)
function isUserInDatabase(serverID, playerID) {
const query = "SELECT * FROM playerdata where serverID=" + serverID + " AND playerID=" + playerID;
return executeQuery(query).then(res => {
const isUndefined = res[0] === undefined
return !isUndefined;
});
}
...
isUserInDatabase("some_server","some_player")
.then( ok => console.log("User is in database!") )
.catch( e => {
console.error(e);
console.log("Error retrieving data from database.");
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…