Node.js: Callback is returning an fault
function die(err) {
console.log('Uh oh: ' + err);
process.exit(1);
}
var box, cmds, next = 0, cb = function(err) {
if (err)
die开发者_Python百科(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 };
});
});
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;
});
});
fetch.on('end', function() {
console.log('Done fetching bodies!');
cb(msgCache);
});
});
},
function(msgs) {
// Do something here with msgs, which contains the headers and
// body (parts) of all the messages you fetched
console.log("HERE");
imap.logout(cb);
}
];
cb();
I'm using that code to get the headers and the body of an e-mail. However, when I try to pass the result (msgCache) it gets an error.
What am I missing here?
It seems like you are calling cb(msgCache) in your fetch on end callback, and cb takes the first argument err. If err is a valid non empty object, then it will call your error handler and die, so it is calling the error handler even with a valid msgCache.
Why not call console.log(msgCache) instead of cb(msgCache) and see if you get through to the end ok.
Or am I missing the point where the error occurs?
精彩评论