Reputation: 814
Should be a fairly simple and quick question, as I am new to using Promises and await/async
This is my original function with Promises. (I want the res.send and res.redirect to happen after the user is created)
router.post('/add', (req, res) => {
const user = req.body.user;
if (user.email && user.username && user.password) {
User.create(createUserObject(user)).then(
res.send(user);
res.redirect('/login'));
}
});
This is my new function with await/async.
router.post('/add', async (req, res) => {
const user = req.body.user;
if (user.email && user.username && user.password) {
await User.create(createUserObject(user));
await res.send(user);
await res.redirect('/login');
}
});
Is it correct that I need await on every line to make the code function the same? I am concerned that I am using await where I don't need to.
Upvotes: 1
Views: 387
Reputation: 565
You don't need to put await in front of every function call, only the ones that are asynchronous and return a promise.
Assuming the line User.create(createUserObject(user))
is the only asynchronous call, that should be the only line that needs an await
.
On the other hand, putting await in front of every function call may not harm your code other than making it look more cluttered.
Upvotes: 0
Reputation: 155015
Is it correct that I need await on every line to make the code function the same?
No. You can do, but you don't need to.
You only need to use await
when a function returns a Promise<T>
. If a function returns a "normal" value (a string
, number
, Object
, etc) then the extra await
will still work but is not needed.
Upvotes: 0
Reputation: 4286
I think this should work
router.post('/add', async (req, res) => {
const user = req.body.user;
if (user.email && user.username && user.password) {
await User.create(createUserObject(user));
res.send(user);
res.redirect('/login');
}
});
The only time you're waiting for something is when you wait for the user to be added to the db. So, wherever you wait for something you'll typically get a promise returned. That's where you can use await.
Upvotes: 2