0
function die(err) {
  console.log('Uh oh: ' + err);
  process.exit(1);
}

var box, cmds, next = 0, cb = function(err) {
  if (err)
    die(err);
  else if (next < cmds.length)
    cmds[next++].apply(this, Array.prototype.slice.call(arguments).slice(1));
};

cmds = [
  function() { imap.connect(cb); },
  function() { imap.openBox('INBOX', false, cb); },
  function(result) { box = result; imap.search([ 'UNSEEN', ['SINCE', 'April 5, 2011'] ], cb); },
  function(results) {
    var msgCache = {},
        fetch = imap.fetch(results, { request: { headers: ['from', 'to', 'subject', 'date'] } });
    console.log('Now fetching headers!');
    fetch.on('message', function(msg) {
      msg.on('end', function() {
        msgCache[msg.id] = { headers: msg.headers };
        console.log(msg.headers.date[0]);
        console.log(msg.headers.to[0]);
        console.log(msg.headers.from[0]);
        console.log(msg.headers.subject[0]);

        var from = /(.*)?<(.*?)>/.exec(msg.headers.from[0]);

        console.log(from[1]); // nome from
        console.log(from[2]); // from
      });
    });
    fetch.on('end', function() {
      console.log('Done fetching headers!');
      console.log('Now fetching bodies!');
      fetch = imap.fetch(results, { request: { headers: false, body: '1' } });
      fetch.on('message', function(msg) {
        msg.data = '';
        msg.on('data', function(chunk) {
          msg.data += chunk;
        });
        msg.on('end', function() {
          msgCache[msg.id].body = msg.data;
            console.log(msg.data);
        });
      });
      fetch.on('end', function() {
        console.log('Done fetching bodies!');
        cb(undefined, msgCache);

      });
    });
  },
  function(msgs) {
    // Do something here with msgs, which contains the headers and
    // body (parts) of all the messages you fetched
//  console.log(msgs);  
    //imap.logout(cb);  

    imap.on('mail', function () {
        // body...
        console.log("New Email Has Arrived!");
        next = 0;
        cb();
    })


  }
];

cb();

When a new e-mail arrives imap.on('mail', function () I want it to run the cb() function again. However, it doesn't do anything after the console.log.

What am I doing wrong?

Thanks

2 Answers 2

1

reset your next counter, and your imap.on('mail', ... should be outside of cmds so that it's not bound again, and again, and again...

Sign up to request clarification or add additional context in comments.

Comments

0

There are some modules around for "flattening" async operations to not end in callback hell.

e.g.: async

Maybe this could help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.