I'm having some trouble figuring out why an object that I pass to another function is not being modified as expected.
Suppose I have the below:
const doSomethingAsync = async ({ data }) =>
new Promise((resolve) => setTimeout(() => {
data = { id: 5 };
resolve();
}, 1000));
const mainFunc = async () => {
let data = {};
console.log('before', data); // prints {}
await doSomethingAsync({ data });
console.log('after', data); // prints {}
}
await mainFunc();
The variable data
never gets changed.
What's weird is that if I change,
let data = {};
to,
const response = {
data: {},
};
then it works just fine:
const doSomethingAsync = async ({ response }) => new Promise((resolve) => setTimeout(() => {
response.data = { id: 5 };
resolve();
}, 1000));
const mainFunc = async () => {
const response = {
data: {},
};
console.log('before', response.data); // prints {}
await doSomethingAsync({ response });
console.log('after', response.data); // prints { id: 5 }
}
await mainFunc();
I know objects are passed by reference, but that's exactly what I'm doing in the first example. What am I doing wrong here?