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

152
Visualizações
Correct way to handle max of independent and dependent async/await jobs (Promises)

I have four asynchronous processes that fetch from different sources, namely process A, B, C and D.

Process A, B and C are independent of each other, but D depends on data from C.

As far as possible, I want A and B to be fetched independently on C and D, but I want to keep the result of A, B, C and D for the procedure that follows.

So I'm trying to come up with the correct way to express this functionality.

Something like

const results = await Promise.allSettled([A, B, C]);
const resultD = await D(results[2].value);

means that I'm waiting to perform D until A, B, C are all finished, but in this case A or B might take significantly more time than C.

Likewise,

const results = await Promise.allSettled([A, B, C, D(await C)]);

Doesn't seem quite right? I don't want C performed twice, and I also want to keep the result.

What would be the correct way to go about solving this elegantly?

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

0

You can group C and D together and resolve it with A and B.

Let's understand the snippet below:

Consider the functions A, B, C & D equivalent to fetching from four different APIs. Also, notice how D needs some data, that it would get from C.

And in the main function we're resolving A, B independently and we're resolving D only after C has finished.

const sleep = (delay, data) => new Promise(res => setTimeout(() => res(data), delay));

const A = () => sleep(100).then(() => "A")
const B = () => sleep(200).then(() => "B")
const C = () => sleep(100).then(() => "C")
const D = (inp) => sleep(100).then(() => inp + "D")


function main() {
  const promises = [A(), B(), C().then(res => D(res))];
  Promise.all(promises).then(console.log);
}

main();

You can also use Promise.allSettled but make sure you understand the difference between allSettled and all.

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