[英]Converting promise-based React app to redux-saga: how do I set React component variables?
[英]How do I debug promise-based code in node?
我正在使用Cujo的偉大When庫為我的Node項目提供Promises / A +實現,盡管這個問題不是特定於節點的。
通常,什么時候很棒:它讓我編寫更易於維護,可讀的代碼。
但是,當我的回調意外失敗(訪問null變量的屬性等)時,異常會被When有效地吞噬,似乎由Promises / A +規范指定 。 不幸的是,這意味着我沒有得到任何關於錯誤的反饋 (除了回調在此時停止執行)。 沒有錯誤類型或消息,沒有行號。
為了顯示:
// hypothetical asynchronous database query
database.query(queryDetails).then(function(result) {
var silly = 3.141592654;
silly(); // TypeError: number is not a function!
process(result); // this code is silently never executed
});
我可以想到一些(不可接受的)方法來解決這個問題:
then
調用(拋售的理由/例外控制台) console.log('I got here 123')
亂丟代碼庫 我只是做錯了嗎? 當然,我並不是唯一一個發現基於promises的代碼可調試性差的人。 有一個明顯的解決方案我錯過了嗎?
2016年9月更新: NodeJS 6.6.0+和7.0+將在未處理的拒絕時自動發出警告。 使用--trace-warnings
運行節點以獲得合理的堆棧跟蹤。 仍然不如藍鳥給你的好,但比以前的情況要好很多。
好的,所以總結評論中的信息並添加一些。
.done
方法來解決這個問題,這會導致拋出未被捕獲的拒絕。 像When和Q這樣的庫以這種方式解決問題。 例如,如果你的.then
之后的.query
是一個.done
你會得到一個很長的堆棧跟蹤。 因此:
require('when/monitor/console'); // when will now log async rejections used with
// `then` , this is experimental in when.
用藍鳥
Promise.longStackTraces(); // Bluebird always logs async rejections but with this
// option it will stitch the asynchronous context stack
// for you in your methods.
以下是我如何檢測Promise在Node上被拒絕但未被捕獲的方式:
if (typeof process === 'object') {
process.on('unhandledRejection', (error, promise) => {
console.error("== Node detected an unhandled rejection! ==");
console.error(error.stack);
});
}
除此之外,您可以使用此Monkey包裝器為Node的ES6 Promises提供長堆棧跟蹤 。 它產生類似於Q的longStackSupport
輸出。 由於性能問題,我不建議在開發代碼之外使用它。 (它在Node v4.4.1中為我工作。我還沒有在Chrome或Firefox中測試它。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.