Home > Mobile >  Unexpected variable values when using await within my server endpoint
Unexpected variable values when using await within my server endpoint

Time:03-20

I have this code extract from my backend:

async function takeTime() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log("resolved");
            resolve(Math.floor(Math.random() * 10));
        }, 5000);
    });
}

app.post('/order', async (req, res) => {
    res.sendStatus(200);
    let order;
    try {
        order = getOrderTemplate(req.body.shipping_address)
        console.log(order.recipient.name)
        await takeTime()
        console.log(order.recipient.name)
    }
    catch (err) {
    }
})

The expected behaviour is, when I send two requests at the same time to the /order endpoint, what I see in the console from console.log(order.recipient.name) should be:

"name1" "name2" "name1" "name2" or if not in that order, it should be two "name1" and two "name2". BUT what I get instead is for example: "name1" "name2" "name2" "name2", where either "name1" or "name2" appear only once.

It MUST have to do something with the fact that there is an await that takes time to finish, but I have no idea why it behaves that way and how to make it work properly.

Not sure if it can help, but the getOrderTemplate function is this:

function getOrderTemplate(shipping_info) {
    const order = { ...order_template };
    order.recipient.name = shipping_info.first_name
    order.recipient.address1 = shipping_info.address1
    order.recipient.city = shipping_info.city
    order.recipient.state_code = shipping_info.province_code
    order.recipient.country_code = shipping_info.country_code
    order.recipient.zip = shipping_info.zip

    order.items = []

    order.packing_slip.email = ""
    order.packing_slip.phone = ""
    order.packing_slip.message = "Welcome!"
    order.packing_slip.logo_url = ""

    return order

}

CodePudding user response:

Your getOrderTemplate makes a shallow copy of order_template. If you are accessing order.recipient its the same object that is in you order_template.

You have to make a deep clone of order_template. If your node isn't too old this can be done with structuredClone.

function getOrderTemplate(shipping_info) {
    const order = structuredClone(order_template);
    ...
    return order
}
  • Related