0

I have a Nodejs structure that separates the router and the controller.

And I try to use Async-Await inside the controller but I get SyntaxError: await is only valid in async function.

Is my syntax wrong?

Why do I get SyntaxError: await is only valid in async function for Await?

routes

const express = require('express');
const router = express.Router();

const authController = require('../controller/auth_controller');

router.post('/login', authController.login);

module.exports = router;

controller

const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const User = require('../model/index');

const { jwtSign } = require('../mixin/jwt');

exports.login = async (req, res, next) => {
  const { email, password } = req.body;
  const secretKey = req.app.get('jwt-secret');

  let sql = `SELECT * FROM user WHERE email = ?`;

  try {
    User.query(sql, [email], (err, result) => {
      ...
      else {
        const token = await jwtSign(secretKey, result[0].userId, email);
      ...
      }
    });
  } catch (error) {
    console.log(error);
  }
};

mixin/jwtSign

const jwt = require('jsonwebtoken');

exports.jwtSign = async (secretKey, userId, email) => {
  const token = jwt.sign(
    {
      userId: userId,
      email: email
    },
    secretKey
  );

  return token;
};

dsfdsf2fafad
  • 321
  • 2
  • 12

1 Answers1

0

You have to replace:

User.query(sql, [email], (err, result) => {

With:

User.query(sql, [email], async (err, result) => {

To make it an async function.

Lioness100
  • 8,260
  • 6
  • 18
  • 49