mscdex / node-imap

An IMAP client module for node.js.
MIT License
2.16k stars 380 forks source link

Multiple callback problem #547

Open NamTThai opened 8 years ago

NamTThai commented 8 years ago

Here is a snippet of me using node-imap

      imap.once('ready', function() {
        imap.openBox(mailboxName, true, function(error, box) {
          if (error) {
            return callback(error);
          }

          imap.search(searchArray, function(error, results) {
            if (error) {
              return callback(error);
            }

            var result = {};
            var f = imap.fetch(results, {
              envelope: true,
              bodies: 'TEXT'
            });

            f.on('message', function(msg, seqno) {
              result[seqno] = {};
              msg.on('body', function(stream, info) {
                var buffer = "";
                stream.on('data', function(chunk) {
                  buffer += chunk;
                });
                stream.once('end', function() {
                  result[seqno].body = buffer;
                });
              });
              msg.once('attributes', function(attrs) {
                result[seqno].attributes = attrs;
              });
            });

            f.once('error', function(error) {
              return callback(error);
            });

            f.once('end', function() {
              imap.end();
              return callback(null, result);
            });
          });
        });
      });

      imap.once('error', function(error) {
        return callback(error);
      });

      imap.connect();

Occasionally when error occurs, I get multiple callback problem: the function callback is supposed to be called only once. My expectation is that when an error occurs, callback triggers and imap just stop doing everything else. But apparently, some later events still trigger, and my callback function gets called again.

Which one is it?

Is it the ImapFetch#end event? Does it get called even after an error occur?

mscdex commented 8 years ago

end will get emitted no matter what, so that is most likely what you're seeing.

NamTThai commented 8 years ago

Is there any alternatives to end that will emit after message but not when error occurs? Like jQuery ajax success event

mscdex commented 8 years ago

Not currently, no.