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.' });
}
});
};
To return promise you need to add return it as it would be normal value. So it should be:
...
const accountBill = `2222${Math.floor(
Math.random() * 90000000000000000000,
) + 10000000000000000000}`;
return Bill.findOne({
where: {
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.