【问题标题】:Promises and nightmareJS in class JavascriptJavascript 类中的 Promise 和 nightmareJS
【发布时间】:2017-11-06 20:48:38
【问题描述】:

所以我有一个运行良好的噩梦代码,我把它放到了一个类中。然而它开始抛出承诺错误:-((没有 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();

错误是:

(节点:1101)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):TypeError:无法读取未定义的属性“噩梦”

(node:1101) [DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

【问题讨论】:

  • 将您的await this.nightmare.goto('https://google.com') 包裹在try catch
  • 你试过await fun();吗?如果在函数初始化之后移动调用会发生什么?

标签: javascript node.js class promise nightmare


【解决方案1】:

这实际上与 promises 或 await 没有任何关系。因为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() 调用它或者您可以手动绑定this,如下所示:

 fun.call(this)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2018-05-25
    • 1970-01-01
    • 2018-10-03
    相关资源
    最近更新 更多