【问题标题】:Getting error on await, that await is valid only on async function when using async function在等待时出错,在使用异步函数时等待仅在异步函数上有效
【发布时间】:2019-08-09 19:31:11
【问题描述】:

我正在使用异步功能来确认数据库中是否存在具有相同用户名或电子邮件的用户。

问题是我在单独的文件中有异步函数。我正在将文件导入到某个端点的路由中。

当我在删除后发送注册用户的请求时

await

从 User.CreateNewUser 和 User.ValidateUserExists 它通过,但是当我再次发送相同的请求时,相同的用户被添加到数据库中而不验证用户是否存在于数据库中。

这是我的路线

const express = require("express");
const router = express.Router();
const asyncHandler = require('../helpers/asyncHandler');
const validate = require('validate.js');
const User = require('../controllers/user-exists-check');


//Route for creating user

router.post('/', asyncHandler((req,res) => {
    const constraints = {
        username: {
            presence: true,
            length:{minimum:4,maximum:10}
        },
        password: {
            presence: true,
            length:{minimum:6, maximum:20} 
        },
        email: {
            presence: true,
            email:true
        }}
    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;
    const permission_id = req.body.permission_id;

    const validation = validate({username, email, password}, constraints);
    if(validation) res.status(400).json({error: validation});

    const existingUser = await User.ValidateUserExists({username, email});
    if(existingUser) {
        if(username === existingUser.username) return res.status(400).json({error:`Username ${username} is already taken`});
        if(email === existingUser.email) return res.status(400).json({error:`Email is already taken`});
    }

    const newUser = await User.CreateNewUser({username, email, password, permission_id});
    return res.status(200).json({user: newUser})

}));


module.exports = router;

这是用户存在检查

const {UserNameExists, EmailExists, CreateUser} = require('./user-db-check');

async function ValidateUserExists(username, email) {
    if(!username || !email ) throw new Error('Not enough args provided')
    let ValidUsername = null;
    let ValidEmail = null;

    if(username) {
        ValidUsername = await UserNameExists(username);
    }
    if(email) {
        ValidEmail = await EmailExists(email);
    }
    if(ValidUsername && ValidEmail) return ValidUsername;
    return null;
}

async function CreateNewUser(args){
    return await CreateUser(args)
}

module.exports = {
    ValidateUserExists,
    CreateNewUser
}

我期待它抛出这个响应

if(username === existingUser.username) 
return res.status(400).json({error:`Username ${username} is already taken`});

if(email === existingUser.email) return res.status(400).json({error:`Email is already taken`});

我使用 await 和 async 的方式是否错误? 谁能赐教一下

【问题讨论】:

  • 试试 -> asyncHandler(async (req,res) => {
  • @keith 你能把它作为答案发布吗,它修复了它,你救了我:) 我还看到我还看到我在函数中发送对象而不是参数:)
  • async-await 不会改变你如何使用函数,只会改变函数的编写方式。 await 只能在内部用于标记为 async 的函数中,无论如何它只是承诺的语法糖,所以从外部角度来看,该函数就像任何其他返回承诺的函数一样。

标签: javascript node.js asynchronous async-await


【解决方案1】:

您的问题是您发送到asyncHandler( 的函数回调未标记为异步,因此您在内部使用的任何函数都不能使用await。

假设你的 asyncHandler 期待一个承诺,那么 asyncHandler(async (req,res) => { 应该可以解决这个问题。

附带说明一下,查看您的代码时,您可能需要考虑一个基本的逻辑问题。在理论上,在多用户环境中执行UserNameExists / EmailExits & 然后CreateUser 仍然可以允许存储相同的用户和电子邮件。大多数数据库都有一种称为事务锁的东西来防止这种情况发生。

【讨论】:

  • 似乎正在发生,但只有电子邮件,谢谢,我现在要把它锁定在我的模型中:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多