【发布时间】:2018-07-07 23:58:20
【问题描述】:
我正在尝试覆盖 then、catch 和 finally 函数。这是为了创建一个全局计数器并监控未决的 Promise。
代码需要执行 Postman Sandbox,所以我不能使用任何 NPM 模块。我需要用 Native JS 来做这个
下面是我正在尝试解决的代码
_constructor = Promise.prototype.constructor
_then = Promise.prototype.then
Promise.prototype.constructor = (...args) => {
console.log("Promise constructor called")
let data = _constructor(...args)
console.log("Promise constructor finished")
return data;
}
Promise.prototype.then = (...args) => {
console.log("then called")
let data = _then.call(this, args)
console.log("then finished")
return data;
}
function test2(num) {
let promise = new Promise((resolve, reject) => {
if (num > 1) {
setTimeout(()=> {
resolve(num)
}, 10)
} else {
reject(num);
}
});
return promise
}
test2(10).then((num) => {
console.log("Inside then")
setTimeout(() => console.log("Promise has been resolved - " + num), 20);
})
但是当我运行它时,我得到以下错误
let data = _then.call(this, args)
^
TypeError: Method Promise.prototype.then called on incompatible receiver #<Object>
at Object.then (<anonymous>)
at Promise.then.args (/Users/tarun.lalwani/Desktop/test/postman/temp.jsx:15:22)
at Object.<anonymous> (/Users/tarun.lalwani/test/postman/temp.jsx:33:11)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:193:16)
我不确定这里出了什么问题,或者这是否正确。
【问题讨论】:
-
这段代码有问题,如果你覆盖“then”并在“then”中调用它,那么你将无法在 _then.call(this, args) 上等待,因为你将运行无限递归调用。这意味着您无法跟踪待处理的承诺,因为您的功能是同步的,而无法等待异步调用。你需要做的是创建一个像“myThen”这样的新函数,它会扭曲而不是覆盖它
标签: javascript node.js promise postman es6-promise