Nods.js路由器抛出“ SyntaxError:等待仅在异步函数中有效”

时间:2019-08-11 07:14:07

标签: mysql node.js async-await

我有一个将路由器和控制器分开的Nodejs结构。

我尝试在控制器内部使用Async-Await,但得到SyntaxError: await is only valid in async function

我的语法错误吗?

为什么我得到SyntaxError: await is only valid in async function来等待?

路线

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

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

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

module.exports = router;

控制器

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;
};

1 个答案:

答案 0 :(得分:0)

您必须替换:

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

使用:

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

使其成为async函数。