承诺或回调,哪一个是更好地使用NodeJS?



我发现使用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 ...)?

这里有一种实现方法,可以进行以下改进:

  1. 使findByEmail()成为一个独立于reqres对象的实用函数,从而可以普遍使用。
  2. 正确地将findByEmail()的所有错误传播回调用者。
  3. 对传入的电子邮件字段进行一些验证检查,并为其设置单独的错误路径。
  4. 记录服务器上的所有错误
  5. 检查数据库请求中的所有错误条件
  6. 不混合.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);
}
});

最新更新