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

341
Views
¿Cómo esperar la promesa en un forEach en JavaScript?

Me gustaría recuperar una matriz de mi colección mongodb y, antes de devolverla al cliente, trabajar con ella. Mi resultado deseado sería el siguiente:

  • Obtener matriz de collection_A
  • Haga el trabajo deseado con la matriz que acabo de obtener, al tener otra consulta mongodb
  • Pasar la matriz de vuelta al cliente

Mi código actual se ve así:

 db.collection("collection") .find() .toArray() .then((arr) => { arr.forEach(cur => { db.collection("another-collection") .count({key: cur.prop}) .then((retrieved) => { cur.prop = retrieved; //The amount of count one live above //This part runs later than the res.success below }) .catch((err: any) => { //Handle error }); }); return arr; }) .then(arr => { res.success(arr); }) .catch((err) => { //Handle error });

Por el momento, el trabajo que quiero hacer con la matriz recuperada ocurre después de res.success() , por lo que en el cliente obtendré la matriz original. ¿Por qué es así?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Puede usar Promise.all junto con Array#map .

 .then((arr) => Promise.all(arr.map(cur => db.collection("another-collection") .count({ key: cur.prop }) .then((retrieved) => { cur.prop = retrieved; return curr; }) .catch((err: any) => { //Handle error }) )) )
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!