javascript - Javascript 类中的 Promise 和 nightJS

标签 javascript node.js class promise nightmare

所以我有这个 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()

您将看到 thisfun() 中未定义。

考虑使 fun() 成为一个真正的方法,并使用 this.fun() 调用它。或者,您可以使用类似的方法手动绑定(bind) this :

 fun.call(this)

关于javascript - Javascript 类中的 Promise 和 nightJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47145518/

相关文章:

javascript - 向请求添加 header 时出现 HTTP 状态代码 405 错误

Javascript 将一个数组对象分配给另一个数组

class - PowerShell 5 和类 - 无法将 "X"类型的 "X"值转换为 "X"类型

javascript - 与 Webpack Dev Server 一起使用时,Webpack 不生成包

javascript - 将全局快捷变量分配给全局命名空间(对象文字)是一种不好的做法吗?

javascript - 避免 c3js 图上的取消选择行为

javascript - 动画不透明度弄乱了我的文字

mysql - 在 Node.js 函数中处理多个相关查询

python - 在 python 中在另一个类中创建一个类的正确方法?

c++ - 将 Vector 与类一起使用时没有运算符错误