mgthomas99
mgthomas99

Reputation: 6694

Return false from Promise: should it resolve(false) or reject()?

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
            }
        });
}

I am unsure how I should handle the resolve/reject calls:

Upvotes: 7

Views: 13822

Answers (1)

mgthomas99
mgthomas99

Reputation: 6694

You should use resolve to return any non-error response, and reject only for errors and exceptions.

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"));
            }
        });
}

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));
            }
        }
}

Upvotes: 10

Related Questions