《深刻淺出Nodejs》時,在第四章 - 異步編程中做者樸靈曾提到,異步編程的難點之一是異常處理,書中描述"嘗試對異步方法進行try/catch操做只能捕獲當次事件循環內的異常,對call back執行時拋出的異常將無能爲力"。編程
//test.js var test = undefined; try{ var f1 = function(){ console.log(test.toString()); } } catch(e){ console.log('error..'); } //assume somewhere f1() will be called as an call back function f1();
這裏模仿f1函數是作爲call back(回調)函數傳遞給其餘函數,在其餘函數執行過程當中執行call back的函數。從代碼表面來看,很容易認爲若是Line 7, 異步
1 console.log(test.toString());
若是這行code發生異常,會天然認爲其會被try catch捕獲到,並不會引發進程的Crash。但其實,運行結果是:異步編程
運行錯誤,Line 11的錯誤並無打印,說明在程序中錯誤沒有被Try Catch。而Nodejs做爲單進程單線程程序,將會引發進程的Crash(崩潰)!函數
------------------------------------------------------------------------------------------------------------------------spa
所以,在進行異步編程時,我的以爲:線程
要考慮到call back函數可能產生的錯誤,增長類型檢查代碼或在Call back被真正執行的地方增長Try cach等,避免異常未能被捕獲致使進程Crashcode
------------------------------------------------------------------------------------------------------------------------blog
如本例,可修改以下,進程
1 if(typeof(test) != 'undefined'){ 2 console.log(test.toString()); 3 }
或者事件
1 console.log(test? test.toString() : '[undefine]');
或者
try{ f1(); } catch(e) { console.log('new error..'); }