Below is my controller from user registration. Before registering, I would like the getAccountBill method to return the result, because it returned null before using async / await. I have now a this error:
const user = await User.create({
^^^^^
SyntaxError: await is only valid in async function
Controller:
// Register Action
exports.register = (req, res) => {
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;
}
User.findOne({
where: { login: req.body.login },
}).then(isUser => {
if (!isUser) {
bcrypt.hash(req.body.password, 10, (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.' });
}
});
};
What is the problem?
Below is my controller from user registration. Before registering, I would like the getAccountBill method to return the result, because it returned null before using async / await. I have now a this error:
const user = await User.create({
^^^^^
SyntaxError: await is only valid in async function
Controller:
// Register Action
exports.register = (req, res) => {
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;
}
User.findOne({
where: { login: req.body.login },
}).then(isUser => {
if (!isUser) {
bcrypt.hash(req.body.password, 10, (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.' });
}
});
};
What is the problem?
Share Improve this question edited Jan 20, 2019 at 18:00 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Jan 20, 2019 at 17:58 asyncawaintreactasyncawaintreact 291 silver badge3 bronze badges 5- 2 What's unclear from that error message? – jonrsharpe Commented Jan 20, 2019 at 17:59
-
2
Well the error message is pretty clear; you can only use
await
inside anasync
function. – Pointy Commented Jan 20, 2019 at 17:59 - I would like to show me, how could I write this controller correctly. – asyncawaintreact Commented Jan 20, 2019 at 18:00
- Did you try making the function in which you're trying to use await an async function? – jonrsharpe Commented Jan 20, 2019 at 18:03
- 2 Possible duplicate of await is only valid in async function - when using mongoosejs exec() – str Commented Jan 20, 2019 at 18:04
2 Answers
Reset to default 3Wel to stackoverflow, try this solution.
The await
keyword is only valid inside async
functions. If you use it outside of an async
function's body, you will get a SyntaxError
.
So you must make the change here:
bcrypt.hash(req.body.password, 10, async (err, hash) => { ...
Also, I made corrections to your code to work properly, check it out and happy coding!
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.' });
}
});
}
I believe it could be fixed by changing this line
bcrypt.hash(req.body.password, 10, (err, hash) => {
to
bcrypt.hash(req.body.password, 10, async (err, hash) => {