用Promises链接的方法

时间:2018-05-28 23:21:50

标签: javascript node.js design-patterns es6-promise

我想实现经典的方法链模式,最终的用法应该是

let nodes = [];
let DB = {
    self:this,
    push: (i) => new Promise((resolve, reject) => {
        nodes.push(i)
        resolve(this)
    })
}

这是当前的代码,显然不起作用,我不清楚如何返回对DB本身的引用来解决这个承诺

{{1}}

1 个答案:

答案 0 :(得分:2)

只有classfunction个实例有this个引用。



class DB {
  constructor() {
    this.nodes = [];
    this.promise = Promise.resolve();
  }
  push(i) {
    this.nodes.push(i);
    return this;
  }
  pushAsync(i) {
    return new Promise((resolve) => {
      this.nodes.push(i);
      resolve();
    });
  }
  pushAsyncChain(i) {
    this.promise.then(() => {
      this.promise = new Promise((resolve) => {
        this.nodes.push(i);
        resolve();
      });
    });
    return this;
  }
  then(callback) {
    this.promise.then(callback);
  }
}

const db = new DB();
db.push(2).push(3);
db.pushAsync(4).then(() => db.pushAsync(5));
db
  .pushAsyncChain(6)
  .pushAsyncChain(7)
  .then(() => console.log(db.nodes)); // or await db.promise; console.log(db.nodes);