所以我有这个 Nightmare 般的代码,它运行得很好,我把它放入一个类中。然而它开始抛出 promise 错误:-((没有 fun() 函数它工作正常。
class test {
constructor() {
this.init(() => {
this.start()
})
}
init() {
this.nightmare = new Nightmare({
show: true,
typeInterval: 20,
openDevTools: {
detach: true
}
});
}
async start() {
await this.nightmare
.useragent(userAgent)
.goto("https://www.yahoo.com")
fun();
async function fun() {
await this.nightmare.goto('https://google.com')
}
}
}
new test().start();
错误是:
(node:1101) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'nightmare' of undefined
(node:1101) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
最佳答案
这实际上与 promise 或等待没有任何关系。您收到错误是因为 this
没有引用 fun()
内的对象。当您创建一个函数并像使用 fun()
一样调用它时,您会丢失对对象的 this
引用。考虑:
class test {
constructor() {
this.init()
}
init() {
this.prop = "a property"
}
start() {
console.log("this outside of fun: ", this)
fun()
function fun(){
console.log("this in fun:", this)
}
}
}
new test().start()
您将看到 this
在 fun()
中未定义。
考虑使 fun()
成为一个真正的方法,并使用 this.fun()
调用它。或者,您可以使用类似的方法手动绑定(bind) this
:
fun.call(this)
关于javascript - Javascript 类中的 Promise 和 nightJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47145518/