Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
¿Cómo evitar el anidamiento de then() con promesas js?

Estoy escribiendo un punto final que modifica el título en una entrada de firebase; luego recopila todas las entradas de Typesense relacionadas con la entrada de Firebase y también las corrige.

Mi código funciona exactamente como yo quisiera. Pero terminé yendo un nivel más profundo con el anidamiento .then() de lo que me hubiera gustado, lo que resultó en 2 declaraciones .catch() en lugar de una.

De alguna manera siento que esto es formalmente incorrecto y me encantaría arreglarlo, pero no sé cómo "salirme" de esto.

 db.collection('posts').doc(post.id) .update({ caption: post.caption }) .then((data) => { // tsense collect all with fireId let searchParameters = { q: '*', filter_by: `fireId:=${post.id}` } TsenseClient.collections(Collection).documents().search(searchParameters) .then((data) => { console.log(data); return data }) .then((tsenses) => { // tsense update all with fireId let tsenseUpdates = [] tsenses.hits.forEach((hit) => { let doc = { "caption": post.caption } tsenseUpdates.push(TsenseClient.collections(Collection).documents(hit.id).search(searchParameters)) }) return Promise.allSettled(tsenseUpdates) }) .then((tsenseUpdates) => { response.send('Update done.') }) .catch((err) => { console.log(err); }) }) .catch((err) => { console.log(err); })
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Por favor, concéntrate en parte

 .then((data) => { // tsense collect all with fireId let searchParameters = { q: '*', filter_by: `fireId:=${post.id}` } TsenseClient.collections(Collection).documents().search(searchParameters) .then((data) => { console.log(data); return data })

y reemplazar con:

 .then((data) => { // tsense collect all with fireId let searchParameters = { q: '*', filter_by: `fireId:=${post.id}` } return TsenseClient.collections(Collection).documents().search(searchParameters) }) .then((data) => { console.log(data); return data })

Puede leer más al respecto https://medium.com/@justintulk/flattening-nested-promises-in-javascript

about 4 years ago · Juan Pablo Isaza Denunciar

0

En lugar de usar then en la promesa TsenseClient , debe devolver la promesa en su lugar y then se habilitará de la siguiente manera:

 db.collection('posts').doc(post.id) .update({ caption: post.caption }) .then((data) => { // tsense collect all with fireId let searchParameters = { q: '*', filter_by: `fireId:=${post.id}` } return TsenseClient.collections(Collection).documents().search(searchParameters) }) .then((data) => { console.log(data); return data }) .then((tsenses) => { // tsense update all with fireId let tsenseUpdates = [] tsenses.hits.forEach((hit) => { let doc = { "caption": post.caption } tsenseUpdates.push(TsenseClient.collections(Collection).documents(hit.id).search(searchParameters)) }) return Promise.allSettled(tsenseUpdates) }) .then((tsenseUpdates) => { response.send('Update done.') }) .catch((err) => { console.log(err); })
about 4 years ago · Juan Pablo Isaza Denunciar

0

considere usar async await , puede encontrar los documentos para la función async en mdn => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

 async function foo() { const p1 = new Promise((resolve) => setTimeout(() => resolve('1'), 1000)) const p2 = new Promise((_,reject) => setTimeout(() => reject('2'), 500)) const results = [await p1, await p2] // Do not do this! Use Promise.all or Promise.allSettled instead.} foo().catch(() => {}) // Attempt to swallow all errors.

ejemplo de fragmento de código img

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda