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

156
Visualizações
Scope of parameter passed to async function
{
  const data = new Uint8Array([0x01]);
  await input_writer.write(data);
}

In the above example, 'data' is passed to an async operation, and then immediately scopes out. What happens to the underlying memory? Does it stay alive until the async function is finished with it?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

At first I thought that data was only garbage collectable at the end of the code block, but it seems that the JavaScript engine is smarter than I thought.

Indeed, when executing this snippet:

class Test {}

(async function() {
  const data = new Test;
  await write(data);
  console.log('never');

  function write(data) {
    return new Promise(() => {});
  }
})();

Then using the "Memory" tab to take a memory snapshot, no Test shows up when searching it.

However, if you try this snippet and take a new snapshot, then the instance shows because this implementation of write passes data to setTimeout which keeps a reference on data for a certain time:

class Test {}

(async function() {
  const data = new Test;
  await write(data);
  console.log('in a long time');

  function write(data) {
    return new Promise(resolve => setTimeout(() => resolve(data), 999999999));
  }
})();

Note: you have to paste it in your console to see it in the memory snapshot.

As a conclusion, if write has no side-effect which saves a reference on data, the JavaScript engine (chromium at least) seems to be smart enough to determine that data won't be used anymore even before the end of the code block, which helps clear the memory as soon as possible.

about 4 years ago · Juan Pablo Isaza Relatório
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