Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
Mutations of object passed to a function are not being applied

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?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda