简体   繁体   English

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

[英]Await is only valid in async function: JavaScript NodeJS

Below is my controller from user registration.以下是我的用户注册控制器。 Before registering, I would like the getAccountBill method to return the result, because it returned null before using async / await.在注册之前,我希望 getAccountBill 方法返回结果,因为它在使用 async/await 之前返回了 null。 I have now a this error:我现在有一个这个错误:

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

What is the problem?问题是什么?

Welcom to stackoverflow, try this solution.欢迎使用 stackoverflow,试试这个解决方案。

The await keyword is only valid inside async functions. await关键字仅在async函数中有效。 If you use it outside of an async function's body, you will get a SyntaxError .如果在async函数的主体之外使用它,则会得到SyntaxError

So you must make the change here:因此,您必须在此处进行更改:

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

Also, I made corrections to your code to work properly, check it out and happy coding!此外,我对您的代码进行了更正以使其正常工作,请检查并快乐编码!

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

I believe it could be fixed by changing this line我相信它可以通过改变这条线来解决

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM