mediumRace ConditionsNode.js
The forgotten await
A developer asked an AI assistant to save an order to the database and then send a confirmation email referencing the saved order's ID. The suggested code runs without errors, but the confirmation email sometimes goes out with 'undefined' as the order ID.
placeOrder.js
async function placeOrder(cart) {
let order;
saveOrder(cart).then((saved) => {
order = saved;
});
await sendConfirmationEmail(order.id);
return order;
}Why does sendConfirmationEmail sometimes receive an order with an undefined id?
saveOrder(cart) throws synchronously whenever the cart is non-empty.
sendConfirmationEmail is being called with the wrong argument name entirely.
await only works on the last statement in an async function, so the first usage is ignored.
The missing await on saveOrder means sendConfirmationEmail runs before the .then callback has a chance to assign order, so order is still undefined.
Sign in with GitHub to submit an answer and track your progress.