从Promise返回false:它应该是resolve(false)还是reject()?

mgt*_*s99 1 error-handling promise

我正在通过HTTP向服务器发出请求,以查看是否存在使用特定电子邮件的用户。

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
            }
        });
}
Run Code Online (Sandbox Code Playgroud)

我不确定应该如何处理resolve/ reject调用:

  • 我应该resolve()何时在数据库中找到用户,以及reject()何时在数据库中找不到用户?
  • 我应该resolve(true)何时在数据库中找到用户,以及accept(false)何时在数据库中找不到用户?

mgt*_*s99 5

您应该使用resolve返回任何非错误响应,并且reject仅返回错误和异常。

在数据库中搜索不包含该条目的特定条目不一定是错误,因此您应该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"));
            }
        });
}
Run Code Online (Sandbox Code Playgroud)

这样可以更轻松地区分returning false和发生错误。

处理回调时,通常会保留第一个返回的参数用于错误响应,而保留其余的参数用于返回值。

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));
            }
        }
}
Run Code Online (Sandbox Code Playgroud)