0

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?

Mike K
  • 7,621
  • 14
  • 60
  • 120
  • Because you're not mutating any object, you're just assigning a new value to a variable. – deceze Feb 09 '22 at 15:43
  • I could be mistaken, but I believe that in the first example you're changing the original reference, where in the second example, the original object is maintained, and the property is changed to a new object reference. – Patrick Barr Feb 09 '22 at 15:43

0 Answers0