You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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.

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 your SELECT EXISTS(...) query always returns exactly one row, which matches what one() expects.
  • You don't need extra if/else checks—result.exists is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:49:43