如何在Koa中使用异步和等待?

问题描述 投票:1回答:1

我创建了一个简单的登录api,但出现404错误。我该如何解决这个问题?我的ctx主体无法正常工作。当我碰到邮递员时,找不到它。

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= $1",
            [`${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",
                    }
                }
            });
});
javascript node.js postgresql koa koa-router
1个回答
0
投票

首先不要将异步与回调和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= $1",  [`${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",
      }

});
© www.soinside.com 2019 - 2024. All rights reserved.