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

213
Visualizações
Primero complete una matriz de promesa, luego complete otra matriz de promesa JavaScript

Tengo un problema con las promesas y no tengo idea de cómo resolver esto:

Mi idea es tener dos métodos que sean un "despachador". En testFetchFaceCharacter() llame a todas las promesas que necesito resolver primero. Necesita todos los datos del state: {Body:{}, TopA:{}, eyes:{}} Cuando testFetchCharacter() , inicie inmediatamente testFetchTopCharacter(), solo si todas las promesas anteriores se ejecutaron correctamente.

Sin embargo, en este punto (con este código) tiene errores. Las promesas no se ejecutan "sincrónicamente". todavía recuperado "asincrónicamente". Cosa que "no debería pasar". Ya que "reduce" (por lo que leí en varios artículos) evitó ese comportamiento.

 const buildCharacter = (state) => { try { testFetchFaceCharacter(state); testFetchTopCharacter(state); } catch (e) { console.error(e + "En buildCharacter"); } const testFetchCharacter = (state) => { const promises = [ fetchCustom(state.Body.id, state.Body.file), fetchCustom(state.TopA.id, state.TopA.file), fetchCustom(state.eyes.id, state.eyes.file), fetchCustom(state.mouth.id, state.mouth.file), fetchCustom(state.nose.id, state.nose.file), fetchCustom(state.eyebrow.id, state.eyebrow.file), fetchCustom(state.Clothing.id, state.Clothing.file), ]; promises.reduce(async (previousPromise, nextPromise) => { await previousPromise return nextPromise }, Promise.resolve()); } const testFetchTopCharacter = (state) => { const promises = [ fetchCustom(state.beard.id, state.beard.file), fetchCustom(state.hat.id, state.hat.file), fetchCustom(state.hair.id, state.hair.file), fetchCustom(state.glass.id, state.glass.file) ]; promises.reduce(async (previousPromise, nextPromise) => { await previousPromise return nextPromise }, Promise.resolve()); }

Prueba esto:

 Execute -> Body Execute -> TopA Execute -> [eyes, mouth, nose, Clothing, eyebrow] //No matter the order then Execute [beard, hat, hair, glass] //not matter the order
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

En primer lugar, hay un error en su código. Debe comprender que tan pronto como llamó a una función, activó una lógica que hace algo, incluso si no escucha la promesa de inmediato, la lógica se está ejecutando.

Entonces, lo que sucedió es que lanzó todas las acciones en "paralelo" cuando realiza llamadas a funciones en la matriz de promises .

Solución A

Debe "posponer" la llamada real de una función hasta que la función anterior se haya realizado correctamente, puede hacerlo manualmente, por ejemplo

 const testFetchTopCharacter = async (state) => { await fetchCustom(state.beard.id, state.beard.file), await fetchCustom(state.hat.id, state.hat.file), await fetchCustom(state.hair.id, state.hair.file), await fetchCustom(state.glass.id, state.glass.file) }

Solución B

Si desea usar el reductor, debe usar la devolución de llamada en esa matriz, de modo que cuando se complete la promesa, llame a la siguiente devolución de llamada en la cadena.

 const testFetchTopCharacter = (state) => { const promises = [ () => fetchCustom(state.beard.id, state.beard.file), () => fetchCustom(state.hat.id, state.hat.file), () => fetchCustom(state.hair.id, state.hair.file), () => fetchCustom(state.glass.id, state.glass.file) ]; promises.reduce((promise, callback) => promise.then(callback), Promise.resolve()); }

Solución C

Si un pedido no te importa, solo haz Promise.all

 const testFetchTopCharacter = (state) => { return Promise.all([ fetchCustom(state.beard.id, state.beard.file), fetchCustom(state.hat.id, state.hat.file), fetchCustom(state.hair.id, state.hair.file), fetchCustom(state.glass.id, state.glass.file) ]); }
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