【问题标题】:Await is only valid in async function: JavaScript NodeJSAwait 仅在异步函数中有效:JavaScript NodeJS
【发布时间】:2019-06-14 05:08:45
【问题描述】:

以下是我的用户注册控制器。在注册之前,我希望 getAccountBill 方法返回结果,因为它在使用 async/await 之前返回 null。我现在有这个错误:

const user = await User.create({
                     ^^^^^
SyntaxError: await is only valid in async function

控制器:

// Register Action
exports.register = (req, res) => {
  function getAvailableFunds() {
    const availableFunds = 0;
    return availableFunds;
  }

  async function getAccountBill() {
    const accountBill = `2222${Math.floor(
      Math.random() * 90000000000000000000,
    ) + 10000000000000000000}`;

    try {
      const isAccountBill = await Bill.findOne({
        where: {
          account_bill: accountBill,
        },
      });
      return isAccountBill ? await getAccountBill() : accountBill;
    } catch(e) {
      console.error(e);
    }
  }

  function getAccountBalanceHistory() {
    const accountBalanceHistory = '0,0';
    return accountBalanceHistory;
  }

  function getTodayDate() {
    const today = new Date();
    return today;
  }

  User.findOne({
    where: { login: req.body.login },
  }).then(isUser => {
    if (!isUser) {
      bcrypt.hash(req.body.password, 10, (err, hash) => {
        req.body.password = hash;

        const user = await User.create({
          login: req.body.login,
          password: req.body.password,
          name: req.body.name,
          surname: req.body.surname,
          email: req.body.email,
          date_registration: getTodayDate(),
        });
        const account_bill = await getAccountBill();
        const bill = await Bill.create({
          id_owner: user.id,
          account_bill,
          available_funds: getAvailableFunds(),
        })
        const additional = await Additional.create({
          id_owner: user.id,
          account_balance_history: getAccountBalanceHistory(),
        });
        res.status(200).json({ register: true });

          }),
        );
      });
    } else {
      res.status(400).json({ error: 'User already exists.' });
    }
  });
};

有什么问题?

【问题讨论】:

  • 该错误消息中有什么不清楚的地方?
  • 嗯,错误信息很清楚;您只能在 async 函数中使用 await
  • 我想告诉我,我怎样才能正确地编写这个控制器。
  • 您是否尝试将您尝试使用 await 的函数设为异步函数?

标签: javascript node.js sequelize.js


【解决方案1】:

我相信可以通过改变这一行来解决它

bcrypt.hash(req.body.password, 10, (err, hash) => {

bcrypt.hash(req.body.password, 10, async (err, hash) => {

【讨论】:

    【解决方案2】:

    欢迎使用 stackoverflow,试试这个解决方案。

    await 关键字仅在 async 函数内有效。如果你在 async 函数体之外使用它,你会得到一个 SyntaxError

    所以您必须在此处进行更改:

    bcrypt.hash(req.body.password, 10, async (err, hash) => { ...
    

    另外,我对您的代码进行了更正以使其正常工作,检查一下,祝您编码愉快!

    function getAvailableFunds() {
            const availableFunds = 0;
            return availableFunds;
        }
    
        async function getAccountBill() {
            const accountBill = `2222${Math.floor(
                Math.random() * 90000000000000000000,
            ) + 10000000000000000000}`;
    
            try {
                const isAccountBill = await Bill.findOne({
                    where: {
                        account_bill: accountBill,
                    },
                });
                return isAccountBill ? await getAccountBill() : accountBill;
            } catch (e) {
                console.error(e);
            }
        }
    
        function getAccountBalanceHistory() {
            const accountBalanceHistory = '0,0';
            return accountBalanceHistory;
        }
    
        function getTodayDate() {
            const today = new Date();
            return today;
        }
    
        // Register Action
        module.exports.register = (req, res) => {
            User.findOne({
                where: { login: req.body.login },
            }).then((isUser) => {
                if (!isUser) {
                    bcrypt.hash(req.body.password, 10, async (err, hash) => {
                        req.body.password = hash;
    
                        const user = await User.create({
                            login: req.body.login,
                            password: req.body.password,
                            name: req.body.name,
                            surname: req.body.surname,
                            email: req.body.email,
                            date_registration: getTodayDate(),
                        });
                        const account_bill = await getAccountBill();
                        const bill = await Bill.create({
                            id_owner: user.id,
                            account_bill,
                            available_funds: getAvailableFunds(),
                        })
                        const additional = await Additional.create({
                            id_owner: user.id,
                            account_balance_history: getAccountBalanceHistory(),
                        });
                        res.status(200).json({ register: true });
                    });
                } else {
                    res.status(400).json({ error: 'User already exists.' });
                }
            });
        }
    

    【讨论】:

      猜你喜欢
      • 2019-09-12
      • 2020-08-13
      • 2022-06-18
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2020-12-23
      • 2020-04-15
      • 1970-01-01
      相关资源
      最近更新 更多