es6 class里的promise
发布于 7 年前 作者 i5ting 3978 次浏览 来自 分享

http://stackoverflow.com/questions/38807521/es6-class-promise-chain-accessing-this


module.exports = class Xxxxx {

  start () {
    let self = this
 
    return this.before()
      .then(this.renderLayout.bind(this))
      .then(this.processError.bind(this))
  }
  
  renderLayout () {
    let self = this
    return self.compile(self.layout, self.data)
  }
 
  
  processError (err) {
    console.log(err)
  }

  before() {
    console.log('after')
  }

  after() {
    console.log('after')
  }
}

备忘一下

return this.before()
      .then(this.renderLayout.bind(this))
      .then(this.processError.bind(this))
5 回复

感觉这个地方写 function () {} 再在里面调用更直观

不错!mark,使用函数的bind绑定上下文,返回新的函数作为then的回调函数

请教狼叔一个问题,nodejs中多个进程同时写一个文件,有没有类似php中的flock这样的锁机制?找了半天都没发现,是不是nodejs中有自己独特的解决办法?

@haozi3156666 每个操作都是promise啊,利用then的机制会比较好

在 constructor 里 bind 一下不更好吗?

class Xxxxx {
	constructor() {
		this.renderLayout = this.renderLayout.bind(this);
    }
}
回到顶部