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

204
Visualizações
Why do these two await lines execute in parallel?

In below code, both c and c2 variables are awaiting for different promise instances and should run in serial but when run, the program completes in 100 miliseconds instead of 200.

function a1() {
  return new Promise((x, y) => {
    setTimeout(function () {
      x(5);
    }, 100);
  });
}

async function run() {
  let t1 = Date.now();
  let b = a1();
  let b2 = a1();

  let c = await b;
  let c2 = await b2;
  console.log(Date.now() - t1);
}

run().then(function () {
  console.log('@');
});

Why is this behavior legal if await is defined as a serial operation?

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

0

You are calling a1() for both b and b2 when declaring them. Thus, by the time you await, the timeouts have already run and they each hold a promise, the await just resolves those promises.

If you want to see the full delay you should asign a1 to your b variables and then await the calls when declaring c, or simply await a1() twice.

  let b = a1;
  let b2 = a1;

  let c = await b();
  let c2 = await b2();

function a1() {
  return new Promise((x, y) => {
    setTimeout(function () {
      x(5);
    }, 100);
  });
}

async function run() {
  let t1 = Date.now();

  let b = await a1();
  let b2 = await a1();
  
  console.log(Date.now() - t1);
}

run().then(function () {
  console.log('@');
});

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