2011-04-05 52 views
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(); 

當新電子郵件到達時imap.on('mail', function()我希望它再次運行cb()函數。但是,它不會在console.log後執行任何操作。Node.js:在事件上運行函數

我在做什麼錯?

感謝

回答

1

重置next計數器,你imap.on('mail', ...應該CMDS以便它不再約束之外,又一次,又一次......

+0

編輯:這是一個連接問題。該解決方案有效。謝謝。 – donald 2011-04-05 22:27:08

0

有一些模塊周圍的「扁平化」異步操作不會在回調地獄中結束。

例如爲:async

也許這可以幫助你。