javascript - 生成随机数并检查它是否存在于数据库中 JavaScript NodeJS

标签 javascript node.js sequelize.js

我的函数生成一个随机数并检查它是否已存在于数据库中。问题是我在注册新用户时使用了这个函数,我需要在这里添加一个 promise ,这样这个函数就不会返回 null。

有人可以告诉我如何编写它,以便我可以确定 return getAccountBill() 将首先完成。

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

    Bill.findOne({
      where: {
        account_bill: accountBill,
      },
    })
      .then(isAccountBill => {
        if (isAccountBill) {
          getAccountBill();
        }
        console.log('accountBill', accountBill);
        return accountBill;
      })
      .catch(err => {
        /* just ignore */
      });
  }

我的注册 Controller :

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

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

    Bill.findOne({
      where: {
        account_bill: accountBill,
      },
    })
      .then(isAccountBill => {
        if (isAccountBill) {
          getAccountBill();
        }
        console.log('accountBill', accountBill);
        return accountBill;
      })
      .catch(err => {
        /* just ignore */
      });
  }

  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;

        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(),
        })
          .then(user =>
            Bill.create({
              id_owner: user.id,
              account_bill: getAccountBill(), // <- this is null
              available_funds: getAvailableFunds(),
            })
              .then(bill => {
                Additional.create({
                  id_owner: user.id,
                  account_balance_history: getAccountBalanceHistory(),
                })
                  .then(() => {
                    res.status(200).json({ register: true });
                  })
                  .catch(err => {
                    res.status(400).json({ error: err });
                  });
              })
              .catch(err => {
                res.status(400).json({ error: err });
              }),
          )
          .catch(err => {
            res.status(400).json({ error: err });
          });
      });
    } else {
      res.status(400).json({ error: 'User already exists.' });
    }
  });
};

最佳答案

给定getAccountBill在内部对 Mongo 进行异步调用,你可以返回他的结果和 await在你打电话之前 Bill.create .

async/await使得以同步方式编写异步代码变得非常容易。

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

  try {
    const acct = await Bill.findOne({
      where: {
        account_bill: accountBill,
      },
    });
    return acct ? await getAccountBill() : accountBill;
  } catch(e) {
    // if you ignore the error, at least log it
    console.error(e);
  }
}

然后在controller中,等待账号,我们再创建账号

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

关于javascript - 生成随机数并检查它是否存在于数据库中 JavaScript NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54276038/

相关文章:

mysql - sequelize 嵌套包含 where 子句

javascript - 将数组插入 const 内 .then

javascript - 变量作用域和事件处理程序

javascript - 将 mongoDB 查询中的表达式替换为数组

javascript - AngularJS自定义指令在继承父范围的同时访问模板中的属性

javascript - Sequelize MYSQL 中的类似字符串匹配

javascript - 带有gmail api的 Node js,API返回错误: Error: unauthorized_client

sql-server - 如何使用 mssql 配置 sequelize?

javascript - 如何在 reactjs ES6 的 JSONArray 上使用 .map() 函数

JavaScript 如何在检测当前域的变量中包含哈希值?