[英]Why promise catch is still getting resolved value
我試圖理解為什么帶有空參數的promise catch仍然獲得解析值1
var x = Promise.resolve(1); var p1 = x.catch(null); p1.then((x) => { console.log(x) }); // logs 1
當x resolves時,它的值為1當您嘗試捕獲x時,它返回x並添加了catch處理程序,因此p1引用x本身,但具有其他catch處理程序現在,因為從x繼承的p1已被解析,因此鏈接任何方法將使用已解析的x參數運行,因此此行為
它返回1,因為您的代碼永遠不會到達catch塊。 要實現它,您必須拒絕您的承諾。 甚至是字面上的( Promise.reject()
)或拋出錯誤:
示例1:一切正常,沒有拒絕:
Promise .resolve(1) .then(x => { console.log(x); return x + 1; }) .then(x => { console.log(x); return x + 1; }) .then(x => { console.log(x); return x + 1; }) .catch(e => { console.log('an error!!'); // block not reached });
示例2:拒絕承諾跳轉到下一個catch塊:
Promise .resolve(1) .then(x => { console.log(x); return x + 1; }) .then(x => { console.log(x); throw Error('ops'); return x + 1; }) .then(x => { // block not reached console.log(x); return x + 1; }) .catch(e => { console.log('an error!!'); });
示例3:catch塊之后,它可以正常運行:
Promise .resolve(1) .then(x => { console.log(x); return x + 1; }) .then(x => { console.log(x); throw Error('ops'); return x + 1; }) .catch(e => { console.log('an error!!'); return 10; }) .then(x => { console.log(x); return x + 1; });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.