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

181
Vistas
Express js Async

When my code is like this, the rendering is early. I want the above processes to run first and then the rendering process (promise). What should I do to fix the problem?

app.get('/inbox', (req, res) => {
  var messagesList = {
    messages: [],
    subjects: [],
    dates: [],
    from: []
  };
  imaps.connect(config).then(function(connection) {

    connection.openBox('INBOX', (err, box) => {

      console.log(box.messages)
      res.locals.box_messages = box.messages;
      var searchCriteria = ['1:' + box.messages.total];
      var fetchOptions = {
        bodies: ['HEADER', 'TEXT', ''],
      };

      connection.search(searchCriteria, fetchOptions).then(function(messages) {

        messages.forEach(function(item) {

          var all = _.find(item.parts, {
            "which": ""
          })
          var id = item.attributes.uid;
          var idHeader = "Imap-Id: " + id + "\r\n";
          simpleParser(idHeader + all.body, (err, mail) => {

            messagesList.messages.push(mail.html)
            messagesList.subjects.push(mail.subject)
            messagesList.dates.push(mail.date)
            messagesList.messages.push(mail.from.text)
            res.locals.messagesList = messagesList
          })
        })
      })
    })

  })
  res.render('index')
})
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You need to change the forEach for a map and make simpleParser asyncronic so it will wait for it to finish before rendering. Try this code:

app.get("/inbox", (req, res) => {
    imaps.connect(config).then(function (connection) {
        connection.openBox("INBOX", (err, box) => {
            console.log(box.messages);
            res.locals.box_messages = box.messages;
            var searchCriteria = ["1:" + box.messages.total];
            var fetchOptions = {
                bodies: ["HEADER", "TEXT", ""],
            };

            connection.search(searchCriteria, fetchOptions).then(async function (messages) {
                var messagesList = {
                    messages: [],
                    subjects: [],
                    dates: [],
                    from: [],
                };
                for(let i = 0; i < messages.length; i++) {
                    var all = _.find(item.parts, { which: "" });
                    var id = item.attributes.uid;
                    var idHeader = "Imap-Id: " + id + "\r\n";
                    try {
                        await new Promise(function (resolve, reject) {
                            simpleParser(idHeader + all.body, (err, mail) => {
                                if (err) reject(err);
                                messagesList.messages.push(mail.html);
                                messagesList.subjects.push(mail.subject);
                                messagesList.dates.push(mail.date);
                                messagesList.messages.push(mail.from.text);
                                res.locals.messagesList = messagesList;
                                resolve(mail);
                            });
                        });
                    } catch (e) {
                        // handle error
                    }
                };
                res.render("index");
            });
        });
    });
});
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