• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

245
Vistas
How to wait for promise in a forEach in JavaScript?

I would like to retrieve an array from my mongodb collection, and before sending it back to the client, work with it. My desired outcome would be the following:

  • Get array from collection_A
  • Do the desired work with the array I just got, by having another mongodb query
  • Pass the array back to the client

My current code looks like this:

                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
                });

At the moment, the work I want to do with the retrieved array happens after res.success(), so on the client I will get the original array. Why is that so?

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use Promise.all along with 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
            })
    ))
)
almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda