生成随机数并检查数据库JavaScript节点中是否存在该随机数

生成随机数并检查数据库JavaScript节点中是否存在该随机数,javascript,node.js,sequelize.js,Javascript,Node.js,Sequelize.js,我的函数生成一个随机数并检查它是否已经存在于数据库中。问题是我在注册新用户时使用了这个函数,我需要在这里添加一个承诺,这样这个函数就不会返回null 有人能告诉我如何编写它,这样我就可以确保首先返回getAccountBill() function getAccountBill() { const accountBill = `2222${Math.floor( Math.random() * 90000000000000000000, ) + 100000000

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

有人能告诉我如何编写它,这样我就可以确保首先返回
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 */
      });
  }
我的注册控制器:

    // 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.' });
    }
  });
};
//注册操作
exports.register=(请求、恢复)=>{
函数getAvailableFunds(){
const availableFunds=0;
返回可用资金;
}
函数getAccountBill(){
const accountBill=`2222${Math.floor(
Math.random()*9000000000000000000,
) + 10000000000000000000}`;
比尔·芬顿({
其中:{
账户账单:账户账单,
},
})
。然后(isAccountBill=>{
if(国际会计准则){
getAccountBill();
}
console.log('accountBill',accountBill);
退票;
})
.catch(错误=>{
/*不管*/
});
}
函数getAccountBalanceHistory(){
const accountBalanceHistory='0,0';
返回账户余额历史记录;
}
函数getTodayDate(){
const today=新日期();
今天回来;
}
User.findOne({
其中:{login:req.body.login},
})。然后(isUser=>{
如果(!isUser){
bcrypt.hash(req.body.password,10,(err,hash)=>{
req.body.password=散列;
User.create({
登录名:req.body.login,
密码:req.body.password,
名称:req.body.name,
姓氏:req.body.姓氏,
电子邮件:req.body.email,
注册日期:getTodayDate(),
})
。然后(用户=>
创建({
id\u所有者:user.id,
账户\账单:getAccountBill(),//{
附加。创建({
id\u所有者:user.id,
账户余额历史记录:getAccountBalanceHistory(),
})
.然后(()=>{
res.status(200).json({register:true});
})
.catch(错误=>{
res.status(400).json({error:err});
});
})
.catch(错误=>{
res.status(400).json({error:err});
}),
)
.catch(错误=>{
res.status(400).json({error:err});
});
});
}否则{
json({error:'用户已经存在。'});
}
});
};

给定
getAccountBill
内部对Mongo进行异步调用,您可以返回他的结果并在调用
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);
  }
}
然后在控制器中,等待帐号,然后再创建帐号

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

const user=wait user.create({
SyntaxError:await仅在异步函数中有效`我编辑了我的帖子,并为register添加了我的所有代码action@ReactRouter4只需将外部函数标记为
async
即可使用
wait
-查看
getAccountBill
函数的示例我尝试了,但我不能一直都使用它。我可以请您向我展示它吗在我的代码示例中?理解这一点对我来说非常重要。