代码之家  ›  专栏  ›  技术社区  ›  alfredopacino

用承诺链接方法

  •  2
  • alfredopacino  · 技术社区  · 6 年前

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

    DB
      .push(2)
      .push(3)
    

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

    let nodes = [];
    let DB = {
        self:this,
        push: (i) => new Promise((resolve, reject) => {
            nodes.push(i)
            resolve(this)
        })
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Roy Wang    6 年前

    只有一个 class function 实例具有 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);