使用pg-promise封装用户名存在判断函数并返回布尔值的正确方式
Fixing the
existsUsername Function with pg-promise Hey there! Let's get that username check function working properly. The main issue with your current code is that you're trying to return a boolean directly from the .then() callback, but this.db.one() returns a Promise—so your function needs to return that Promise, which resolves to the boolean value you want.
Correct Implementation with Async/Await (Recommended)
Async/await makes this code much cleaner and easier to read:
async existsUsername(username) { // The query returns an object like { exists: true } or { exists: false } const result = await this.db.one('SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)', username); // Directly return the boolean value from the result return result.exists; }
Alternative Implementation with .then()
If you prefer using Promise chains instead of async/await, make sure you return the entire Promise chain:
existsUsername(username) { return this.db.one('SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)', username) .then(data => data.exists); // Resolve the Promise with the boolean value }
How to Use the Function
Since both implementations return a Promise, you'll need to handle it with either await (inside an async function) or .then():
// Example with async/await async checkUsernameAvailability(username) { try { const isTaken = await this.existsUsername(username); if (isTaken) { console.log('Oops, this username is already taken!'); } else { console.log('Great, this username is available!'); } } catch (err) { // Handle database errors here (e.g., connection issues, invalid queries) console.error('Error checking username:', err); } } // Example with .then()/.catch() this.existsUsername('jane_smith') .then(isTaken => { if (isTaken) { console.log('Oops, this username is already taken!'); } else { console.log('Great, this username is available!'); } }) .catch(err => { console.error('Error checking username:', err); });
Key Notes
db.one()is perfect here because yourSELECT EXISTS(...)query always returns exactly one row, which matches whatone()expects.- You don't need extra
if/elsechecks—result.existsis already a boolean, so you can return it directly. - Don't forget error handling! Database queries can fail, so always wrap your calls in
try/catch(for async/await) or use.catch()(for Promise chains).
内容的提问来源于stack exchange,提问作者Kathandrax
相关产品推荐
相关产品推荐

