mysql Promise和Callback,哪个更适合NodeJS?

zzlelutf  于 2023-01-12  发布在  Mysql
关注(0)|答案(1)|浏览(146)

我发现使用promisecallback编写节点函数有两种不同的方法,第一种方法类似于定义findByEmail函数:

class Users{
  static async findByEmail(email: any ) : Promise<Users | undefined>{
    const user: any = await Pools.execute(
      "SELECT * FROM users WHERE email = ?",
      [email])
      .then(rows => { 
        return rows[0];
       })
      .catch(err => console.log(err) );
      return user;
  };
}

router.post(
  "/api/users/signin",
  async (req: Request, res: Response , next: NextFunction) => {
     const { email, password } = req.body;
     const existingUser = await Users.findByEmail(email);
});

第二种方法是:

declare global {
  namespace Express {
    interface Response {
      user?: Users;
    }
  }
}

  static async findByEmail(req: Request, res: Response) {
    const user = await Pools.execute(
      "SELECT * FROM users WHERE email = ?",
      [req.body.email])
      .then(rows => { 
         res.user = rows[0];
       })
      .catch(err => console.log(err) );
  };



router.post(
  "/api/users/signin",
  async (req: Request, res: Response , next: NextFunction) => {
    await Users.findByEmail(req, res);
    const existingUser = res.user;
});

我不确定这是否是一个“基于意见”的问题?但是我问这个问题的目的是想知道哪种方式是更好的实践,为什么?根据性能和其他可能的问题?

特别是我想知道用return值编写函数或使用response对象将返回值添加到then()函数内部的值是否更好,例如.then(res.user = user)而不是const user = await pool.execute(SELECT ...)

yqhsw0fo

yqhsw0fo1#

这里有一种穿刺方法,可以进行以下改进:
1.使findByEmail()成为独立于reqres对象的实用函数,因此可以通用。
1.正确地将所有错误从findByEmail()传播回调用方。
1.实现了一些验证检查传入的电子邮件字段,并使单独的错误路径.
1.记录服务器上的所有错误
1.检查数据库请求中的所有错误条件
1.不混合.then()await
下面是代码:

// resolves to null if email not found
// rejects if there's a database error
static async findByEmail(email) {
    const rows = await Pools.execute("SELECT * FROM users WHERE email = ?", [email]);
    if (!rows || !rows.length || !rows[0]) {
        return null;
    }
    return rows[0];
};

router.post("/api/users/signin", async (req: Request, res: Response, next: NextFunction) => {
    try {
        // validate incoming parameters
        if (!req.body.email) {
            let errMsg = "No email value present in incoming signin request";
            console.log(errMsg);
            res.status(400).send(errMsg);
            return;
        }
        let user = await Users.findByEmail(req.body.email);
        if (!user) {
            // do whatever you would do if user tries to signin with non-existent email
            // presumably return something like a 404 status
        } else {
            // do whatever you wanted to do here with the user object after login
        }
    } catch(e) {
        // some sort of server error here, probably a database error, not the client's fault
        console.log(e);
        res.sendStatus(500);
    }
});

相关问题