Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
¿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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!