I have a user object that looks like this:
{
name: "john",
cart: [1, 2, 3]
}
This object is posted to my express.js web app. On certain routes a lot of middleware acts on that object, and it is also sent back to the user.
The issue is that some of the middleware, which operates on the user is asynchronous and modifies the user object. Also I try to send the user object back in the response as soon as possible.
Given that Javascript uses call-by-sharing, I am not sure what happens to the object as its properties are modified by async functions (perhaps before the object is sent back). Here is what I am talking about.
// This would be called after a post request
app.use(function (req, res, user) {
asyncSaveCartInDataBase(user, function (user) {
// Just an example
user.cart.push('things')
})
user.cart = []
res.json(user);
});
Here, asyncSaveCartInDataBase is called, which needs the full, unmodified cart property of the user. However, in an effort to send back the response from my server as soon as possible (and because user.cart will always be an empty array at the end) I set user.cart to an empty array and immediately send it back.
If JS made a copy of the object I wouldn't have to worry, but it does not, so I do not know what the value of user.cart is when it comes to the callback of asyncSaveCartInDataBase.
Is there a way to use the async nature of JS and node to change user.cart property and immediately send it back while not modifying the property for it's use in the asynchronous functions. Do I have to make a deep clone or something?
userand send that with an empty array instead?user.cart, register a response, then restore the cart to the user.