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.
3 Answers 3
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.
6 Comments
res.send(user); and res.redirect('/login'); are currently inside the .then callback (your first example is invalid so we don't know) and it works correctly, then yes, this await version will be equivalent.awaited.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.
Comments
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.
Promise<T>and when it doesn't. That said, usingawaitwith a non-Promise will work.awaitdoes: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… .async/awaitis syntactic sugar to work with promises.awaitonly makes sense to use if the value you are trying toawaitis a promise.