2017-08-15 100 views
1

我想攔截所有承諾然後方法的響應。但我無法在原型和方法中獲得響應數據。請找到下面的代碼。如何攔截Promises響應或捕獲?

(function(Promise) { 
    var originalThen = Promise.prototype.then; 
    var originalCatch = Promise.prototype.catch; 
    Promise.prototype.then = function() { 
     console.log(this, arguments); 
     return originalThen.apply(this, arguments); 
    }; 
    Promise.prototype.catch = function() { 
     return originalCatch.apply(this, arguments); 
    }; 
})(this.Promise) 

在上面的代碼中,我可以看到在所有Promise調用中打印的控制檯。但是我無法獲得當時的響應對象。

印刷 '這個' 對象在控制檯值:

enter image description here

的 '然後' 原型方法中的印刷參數:

enter image description here

請建議我在所有promise方法的then方法中獲得響應對象。

我就先用「的論點[0] .arguments」(在當時的回調Response對象),但它拋出下面的錯誤

Uncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.

請建議我解決攔截響應值目的。

在此先感謝。

+1

你將高達擬訂關於爲什麼呢? – loganfsmyth

回答

2

then()在承諾實際上具有值之前消費承諾來添加回調時被調用。
它的參數是成功和錯誤回調。

要查看承諾的價值,您需要實際撥打then()並傳遞迴調以查看其最終價值。 (或者包裝您通過的回調並將您的包裝傳遞給真實的then()

3

then是一種同步方法,用於註冊成功和失敗回調。它立即返回。

攔截未來值,插入自己在地方的成功回調:

(function(Promise) { 
 
    var originalThen = Promise.prototype.then; 
 
    Promise.prototype.then = function(onFulfilled, onFailure) { 
 
     return originalThen.call(this, function(value) { 
 
     console.log(value); 
 
     return onFulfilled(value); 
 
     }, onFailure); 
 
    }; 
 
})(this.Promise); 
 

 
Promise.resolve(3).then(() => console.log("Done"));