Reputation: 1228
I made an api like below.
I think it works asyncrously well without doubt.
exports.query = async(req, res) => {
try{
const result = await user.findOne({})
res.send(result);
} catch(error) {
res.send(error)
}
}
But when I try this like below, I am not sure it works asyncrously or not.
exports.query = async(req, res) => {
try{
user.findOne({})
.then(async(result) =>{
order.findOne({id: result.id})
.catch(e => res.send(e)
} catch(error) {
res.send(error)
}
}
I have to attach 'await' in front of user.findOne({}) like below?
exports.query = async(req, res) => {
try{
await user.findOne({})
.then(async(result) =>{
Or it doesn't matter? That is, it works same asycrously, even though I don't write await in front to user.findOne using 'then'?
thank you so much for reading.
Upvotes: 0
Views: 294
Reputation: 1337
First of all, async-await can be used in functions which returns a promise.
Why we have to use await
instead of then
. await
process the code asynchronously by making the execution feel like synchronous.
In your first example, everything works fine as expected. But in the second one, you need to await the findOne query. Here the fineOne will work asynchronously
exports.query = async(req, res) => {
try{
user.findOne({})
.then(async(result) =>{
let orderResult = await order.findOne({id: result.id})
.catch(e => res.send(e)
} catch(error) {
res.send(error)
}
}
which can be again simplified to
exports.query = async(req, res) => {
try{
let result = await user.findOne({});
let orderResult = order.findOne({id: result.id});
} catch(error) {
res.send(error)
}
}
Upvotes: 0
Reputation: 370639
Generally, inside a single block, you should either use await
, or use .then
, but not both - similarly, using Promise.prototype.catch
is really weird in combination with try/catch
where you can already await
.
For your exports.query
to resolve once the second findOne
finishes, await
or return both Promises, and connect the inner findOne
connected to the outer Promise chain. Consider something like this instead:
exports.query = async (req, res) => {
try {
const userResult = await user.findOne({});
const orderResult = await userResult.findOne({ id: userResult.id });
// do something with orderResult
} catch (error) {
res.send(error)
}
}
If you use .then
and catch
without await
, then it would look like:
exports.query = (req, res) => {
return user.findOne({})
.then((result) => {
return order.findOne({
id: result.id
})
.then((orderResult) => {
// do something with orderResult
})
.catch(e => res.send(e))
});
}
With the code in the second snippet in your question, your try
/catch
block will never do anything useful, because any problem will trigger the .catch
method, and because the Promise isn't being await
ed. Better not to mix the two styles - either pick await
and try
/catch
or .then
and .catch
, but not both, else the control flow may become difficult to make sense of.
Upvotes: 1