2011-04-05 62 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 }; 
     }); 
    }); 
    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(); 

我正在使用該代碼來獲取電子郵件的標題和正文。但是,當我嘗試傳遞結果(msgCache)時,它會得到一個錯誤。Node.js:回調正在返回一個錯誤

我在想她嗎?

謝謝。

回答

1

看起來你在調用cb(msgCache)的時候會在你的回調結束時回調,而cb會接受第一個參數err。如果err是一個有效的非空對象,那麼它會調用你的錯誤處理程序並死掉,所以即使有一個有效的msgCache它也會調用錯誤處理程序。

爲什麼不調用console.log(msgCache)而不是cb(msgCache)並查看您是否完成了正確的操作。

或者我錯過了發生錯誤的地方?

+0

看來你是對的,cb(undefined,msgCache);解決了這個問題。 – donald 2011-04-05 18:49:29