I think I understand async/await but I am confused by a part I have reached in my code in a very common scenario.
I have an async function createOrder()
that processes orders. Before that function returns any values, it needs to execute another async function to send email confirmation sendEmail()
.
I don't want to wait for the email to be sent before returning the order details back to the customer.
So this is how I have gone about it:
async function createOrder(){
try {
//Create the order object
const order = {
productid: 1234
name: "helpful text"
price: "55.00"
}
sendEmail(order); // I dont want to await this
return {
order // Client needs this ASAP without waiting for email to be sent
}
}
catch (e) {
console.error(e);
}
}
The email function sends the mail:
async function sendEmail(payload){
try {
await axios.post('/emailer/send', {
payload
});
}
catch(e){
console.error(e);
}
}
My question is that my IDE gives me a warning that I have not used await
when calling the sendEmail()
function. Is it just a suggestion or is there something fundamentally wrong with my approach? If I am wrong, then what is a better way to go about it?
Usually the issue is that if sendEmail
fails, you would want to handle that exception. But in this case, sendEmail
has a try catch in itself, so you should be fine.
Unless there is more logic inside sendEmail
which is not mentioned or say console.error
is undefined
, you are good.