从Promise返回false:它应该是resolve(false)还是reject()? [英] Return false from Promise: should it resolve(false) or reject()?
问题描述
我正在通过HTTP向服务器发出请求,以查看是否存在使用特定电子邮件的用户。
I am making a request to a server via HTTP, to see if a user with a specific email exists.
function userExists(id) {
return makeHttpRequestToServer(id)
.then((response) => {
if (response === 200) {
// User exists in the database
} else if (response === 404) {
// User does not exist in the database
}
});
}
我不确定应该如何处理 resolve
/ 拒绝
呼叫:
I am unsure how I should handle the resolve
/reject
calls:
- 我应该<$ c在数据库中找到用户时是$ c> resolve(),在数据库中找不到用户时是
reject()
? / li>
- 当在数据库中找到用户时,我应该
resolve(true)
,并且accept(false)
当在数据库中找不到用户时?
- Should I
resolve()
when the user is found in the database, andreject()
when the user is not found in the database? - Should I
resolve(true)
when the user is found in the database, andaccept(false)
when the user is not found in the database?
推荐答案
您应该使用 resolve
返回任何非错误响应,而 reject
仅用于错误和异常。
You should use resolve
to return any non-error response, and reject
only for errors and exceptions.
在数据库中搜索不包含该条目的特定条目不一定是错误,因此您应该 resolve(false)
Searching for a specific entry in a database that does not contain the entry is not necessarily an error, so you should resolve(false)
.
function userExists(id) {
return makeHttpRequestToServer(id)
.then((response) => {
if (response === 200) {
// User exists in the database
resolve(true);
} else if (response === 404) {
// User does not exist in the database
resolve(false);
} else {
// Something bad happened
reject(new Error("An error occurred"));
}
});
}
这样可以更容易地区分返回 false
,并发生错误。
This makes it easier to differentiate between returning false
, and having an error occur.
在处理回调时,通常会保留第一个返回的错误响应参数,其余的用于返回值。
When handling callbacks, it is conventional to preserve the first returned argument for error responses, and the remaining arguments for returned values.
function userExists(id, callback) {
makeHttpRequestToServer(id)
.then((response) => {
if (response === 200) {
// User exists in the database
callback(undefined, true);
} else if (response === 404) {
// User does not exist in the database
callback(undefined, false);
} else {
// Something bad happened
callback(new Error(response));
}
}
}
这篇关于从Promise返回false:它应该是resolve(false)还是reject()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!