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.
awaitto suspend the execution of theasyncfunction pending on the promise returned by your chain. Your second example will not work, and additionally it contains a syntax error.thento chain each of theasyncfunctions or useasync/awaitcombination to run theasynccodeawait user.findOne({});and so on with atry/catchto handle errors. And don't mix these patterns altogether.asyncfunction but don'tawaitor return a Promise, the Promise returned by the function will resolve immediately, which is usually not desirable - generally, it's best to return a Promise that resolves when the function is done with all of its work