如何在koa中使用async和await?
how to use async and await in koa?
我创建了一个简单的登录 api 但我收到 404 错误。我该如何解决这个问题?我的 ctx body 不工作。当我碰到邮递员时,它抛出找不到。
router.post('/login', async (ctx, next) => {
var phone= ctx.request.body.phone;
var password = ctx.request.body.password;
await ctx.app.pool.query("SELECT * FROM users WHERE phone= ",
[`${phone}`],
async (err, result) => {
if (result) {
await bcrypt.compare(password, result.rows[0].password).then(function (res) {
if (res === true) {
ctx.body = {
status: 200,
message: "login successfully",
data: result.rows[0],
};
}else{
ctx.body = {
status: 400,
message: "Incorrect password! Try again.",
}
}
});
}else{
ctx.body = {
status: 400,
message: "Invalid phone",
}
}
});
});
首先不要将异步与回调混合使用 & then
使用const res = await somepromise()
您为查询使用了回调,为 bcrypt.compare 使用了 then
而不是等待它
router.post('/login', async (ctx, next) => {
const phone= ctx.request.body.phone;
const password = ctx.request.body.password;
const result = await ctx.app.pool.query("SELECT * FROM users WHERE phone= ", [`${phone}`])
if (result) {
const pwCorrect = await bcrypt.compare(password, result.rows[0].password)
if (pwCorrect === true) {
ctx.body = {
status: 200,
message: "login successfully",
data: result.rows[0],
};
}else{
ctx.body = {
status: 400,
message: "Incorrect password! Try again.",
}
}
} else{
ctx.body = {
status: 400,
message: "Invalid phone",
}
});
我创建了一个简单的登录 api 但我收到 404 错误。我该如何解决这个问题?我的 ctx body 不工作。当我碰到邮递员时,它抛出找不到。
router.post('/login', async (ctx, next) => {
var phone= ctx.request.body.phone;
var password = ctx.request.body.password;
await ctx.app.pool.query("SELECT * FROM users WHERE phone= ",
[`${phone}`],
async (err, result) => {
if (result) {
await bcrypt.compare(password, result.rows[0].password).then(function (res) {
if (res === true) {
ctx.body = {
status: 200,
message: "login successfully",
data: result.rows[0],
};
}else{
ctx.body = {
status: 400,
message: "Incorrect password! Try again.",
}
}
});
}else{
ctx.body = {
status: 400,
message: "Invalid phone",
}
}
});
});
首先不要将异步与回调混合使用 & then
使用const res = await somepromise()
您为查询使用了回调,为 bcrypt.compare 使用了 then
而不是等待它
router.post('/login', async (ctx, next) => {
const phone= ctx.request.body.phone;
const password = ctx.request.body.password;
const result = await ctx.app.pool.query("SELECT * FROM users WHERE phone= ", [`${phone}`])
if (result) {
const pwCorrect = await bcrypt.compare(password, result.rows[0].password)
if (pwCorrect === true) {
ctx.body = {
status: 200,
message: "login successfully",
data: result.rows[0],
};
}else{
ctx.body = {
status: 400,
message: "Incorrect password! Try again.",
}
}
} else{
ctx.body = {
status: 400,
message: "Invalid phone",
}
});