javascript - Await 仅在异步函数中有效 : JavaScript NodeJS

标签 javascript node.js sequelize.js

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

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

Controller :

// 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.' });
    }
  });
};

问题是什么?

最佳答案

欢迎来到 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.' });
            }
        });
    }

关于javascript - Await 仅在异步函数中有效 : JavaScript NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279317/

相关文章:

javascript - 如何让 KnockOutJS 识别具有数据绑定(bind)属性的动态 html?

javascript - 调用对象数组时无法读取未定义的属性 'teacherId'

javascript - 将 Ember.js 与 Fabric.js 等 Canvas 库集成的正确方法是什么?

javascript - 如何防止 "MongoError: Transaction 1 has been committed."?

sql-server - 如何使用 sequelize 在 where 对象中指定外部模型上的列?

node.js - 如何使用 Sequelize 在迁移中添加对另一个表列的引用作为外键

javascript - VueJs - 通过过渡更改 div 颜色

node.js - 设计实时 Web 应用程序(Node.js 和 socket.io)

javascript - Mongoose:需要验证错误路径

javascript - SQL 到 Sequelize 转换