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

能否简化这段Passport身份验证代码?

Optimizing Passport User Creation by Cutting Redundant Database Calls

Looking at your Passport authentication code, you’ve spotted a perfect opportunity to simplify the logic without losing any reliability. Let’s walk through why the original approach has unnecessary overhead, then review the optimized version.

Original Code

The original implementation creates a user, then immediately fetches the same user data from the database to pass to the done() callback:

// the user was not found
// create the user, get the user, and return the user object
function createUser (done, profile) {
  let props = obtainProps(profile);
  DBM.createUser(props).then(() => {
    DBM.getUser(props.id_google).then((res) => {
      return done(null, res[0]);
    }).catch( error => {
      return done(error, null);
    });
  });
}

Why This Is Redundant

The original author probably added the post-creation fetch to "confirm" the save worked, but this step is unnecessary:

  • If DBM.createUser(props) resolves successfully, we already know the user data was persisted correctly—any failures would be caught in the .catch() block.
  • The props object already holds all the data we just saved to the database. There’s no value in retrieving it again.

Optimized Code

We can remove the extra getUser call entirely and return the props object directly once the creation succeeds:

// the user was not found
// create the user then return props
function createUser (done, profile) {
  let props = obtainProps(profile);
  DBM.createUser(props).then(() => {
    return done(null, props);
  }).catch( error => {
    return done(error, null);
  });
}

Key Advantages

  • Less database overhead: One fewer round trip to the database for every new user creation.
  • Simpler, cleaner code: The logic is more straightforward and easier to debug or modify later.
  • No loss of reliability: We still handle errors properly, and we’re passing along the exact data that was confirmed to be saved.

内容的提问来源于stack exchange,提问作者user9723618

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:46:58