Blockchain Expert
Blockchain Expert

Reputation: 55

How return the imap results from a node api server?

I'm setting up an API server in nodejs for parsing emails from my Gmail account using the IMAP node module. But when I call the request /api/fetch-email from my angular app, it returns the control before email parsing completes.

My api server file

    app.get('/api/fetch-email', async (req, res, next)=>{
      let emails = await email.email();
      console.log(console.log);
    });

email.js module

    var Imap = require('imap'),
    inspect = require('util').inspect;

    let email_array = [];

    var imap = new Imap({
      user: 'myemail',
      password: 'password',
      host: 'imap.gmail.com',
      port: 993,
      tls: true
    });


    let email = async()=>{
      imap.connect();

      return imap.once('end', async function() {
        console.log('Connection ended');
        return new Promise((resolve, reject)=>{
         resolve(email_array);
         flag = true
        });
      });
    }

    exports.email = email;

    function openInbox(cb) {
      imap.openBox('INBOX', true, cb);
    }

    imap.once('ready', function() {
      email_array = [];
      flag = false;
      openInbox(function(err, box) {
        if (err) throw err;
        imap.search([ ['SUBJECT', 'TEST'], ['ON', 'Oct 7, 2019']], 
        async function(err, results) {
          if (err) throw err;
          var f = imap.fetch(results, { bodies: '' });

          var root = builder.create('blocktick');
          f.on('message', function(msg, seqno) {
            console.log('Message #%d', seqno);
            var prefix = '(#' + seqno + ') ';

            msg.on('body', function(stream, info) {
              const chunks = [];

              stream.on("data", function (chunk) {
              chunks.push(chunk);
            });

            stream.on("end", function () {
              let string = Buffer.concat(chunks).toString('utf8');
              email_array.push(string);
            });
          });

          msg.once('end', function() {
            console.log(prefix + 'Finished');
          });
        });
        f.once('error', function(err) {
          console.log('Fetch error: ' + err);
        });
        f.once('end', function() {
          console.log('Done fetching all messages!');
          imap.end();
          });
        });
      });
    });

    imap.once('error', function(err) {
      console.log(err);
    });

The console returns undefined on api call. How can I make this call synchronous?

Upvotes: 5

Views: 1752

Answers (1)

iAmADeveloper
iAmADeveloper

Reputation: 667

You are returning the return value of imap.once function call. You need to rewrite this code like this.

let email = async () => {
      imap.connect();
      return new Promise((resolve, reject) => {
        imap.once('end', async function () {
          console.log('Connection ended');
          resolve(email_array);
          flag = true
        });
      })
    }

Upvotes: 3

Related Questions