Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number and check if this exist in database JavaScript NodeJS

My function generates a random number and checks if it already exists in the database. The problem is that I use this function when registering a new user and I need to add a promise here so that this function does not return null.

Could someone show me how I can write it, so that I can be sure that return getAccountBill() will be done first.

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

My register 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.' });
    }
  });
};
like image 213
ReactRouter4 Avatar asked Feb 04 '26 12:02

ReactRouter4


1 Answers

Given getAccountBill internally makes async calls to Mongo, you can return his result and await it before you call Bill.create.

async / await makes writing async code in a synchronous way pretty easy.

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

Then in the controller, wait for the account number before we create the account

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 });
like image 197
James Avatar answered Feb 06 '26 01:02

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!