以下是我的用户注册控制者。在注册之前,我希望getAccountBill方法返回结果,因为在使用异步/等待之前它返回了null。我现在有一个错误:
fields={fieldname1,fieldname2}
控制器:
const user = await User.create({
^^^^^
SyntaxError: await is only valid in async function
出什么问题了?
答案 0 :(得分:1)
欢迎使用stackoverflow,请尝试以下解决方案。
await
关键字仅在async
函数内部有效。如果在async
函数的主体外部使用它,则会得到SyntaxError
。
因此您必须在此处进行更改:
bcrypt.hash(req.body.password, 10, async (err, hash) => { ...
此外,我还对您的代码进行了更正,以使其正常工作,请检查并满意代码!
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.' });
}
});
}
答案 1 :(得分:0)
我相信可以通过更改此行来解决
bcrypt.hash(req.body.password, 10, (err, hash) => {
到
bcrypt.hash(req.body.password, 10, async (err, hash) => {