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

261
Visualizações
Order of execution of back to back JavaScript Promises

In the following code:

new Promise((resolve, reject) => {
    asyncFunc1(resolve,reject);
})
    .then((result) => {
        // do then1 stuff
    })
    
    
new Promise((resolve, reject) => {
    asyncFunc2(resolve,reject);
})
    .then((result) => {
        // do then2 stuff
    })

Will asyncFunc1()'s .then() complete before asyncFunc2() is executed?

Or will both execute (nearly) simultaneously, and their then()s execute just whenever they happen to return?

If the second one does not wait for the first one, is there a way to make it do so other than moving asyncFunc2() into asyncFunc1()'s .then()?

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

0

Both promises will execute (nearly) simultaneously, because that is exactly one of the strengths of Javascript: Due to its callback-based design, it can kick off and wait for many asynchronous functions (in the form of promises) in parallel, without the need for the developer to care about complex handling of threads or anything like that.

If you want to have asyncFunc2 wait for the completion of asyncFunc1, it needs to be placed inside the then-block of asyncFunc1.

You can easily see and proof that by simulating two functions which take a defined time (using setTimeout), for example:

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved at ' + new Date().toISOString());
    }, 2000);
  });
}

function resolveAfter3Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved at ' + new Date().toISOString());
    }, 3000);
  });
}

function execPromises() {
  console.log('calling at '  + new Date().toISOString());
  resolveAfter2Seconds().then(result => console.log(result));
  resolveAfter3Seconds().then(result => console.log(result));
}

execPromises();

You will see in the console output that the first one will finish 2 sec after starting the script, the other one 3 sec after starting the script (and not after 2 + 3 = 5 sec).

If you want to make asyncFunc2 wait for asyncFunc1 without the need for then, you can use the async/await keywords.

In my example, the function execPromises would then look like this (asyncFunc2 executed after completion of asyncFunc1!):

async function execPromises() {
  console.log('calling at '  + new Date().toISOString());
  const resultA = await resolveAfter2Seconds();
  console.log(resultA);
  const resultB = await resolveAfter3Seconds();
  console.log(resultB);
}
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