【问题标题】:Method chaining with Promises使用 Promises 链接方法
【发布时间】:2018-11-07 12:35:03
【问题描述】:

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

DB
  .push(2)
  .push(3)

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

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

【问题讨论】:

  • 真正的代码当然要复杂得多

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


【解决方案1】:

只有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);

【讨论】:

  • 谢谢。你为什么说我不返回承诺?另外,我想知道是否有办法(使用 async/await)避免在类外使用 then() ..为了保持异步使用,如 db.push(2).push(3)
  • async 只能在函数内消除.then,不能在函数外消除。您的其他选项包括使用回调:db.push(2, db.push(3)),传递数组:db.push([2, 3]),或在调用者中使用等待:await db.pushAsync(2); await db.pushAsync(3)。也许提供更多关于您的实际用例的详细信息以及为什么上述解决方案有问题?
  • 您的解决方案没有问题,只是不是真正的方法链。我会使用你的class 解决方案,谢谢
  • 刚刚想到了一种实现异步链接的方法。见编辑。不过,您仍然需要处理调用者链中的最终承诺。
  • 谢谢,您的示例甚至可以帮助我了解 Promises 的详细工作原理。
猜你喜欢
  • 2014-12-13
  • 2017-10-30
  • 1970-01-01
  • 2015-06-23
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 2017-05-09
  • 2021-10-19
相关资源
最近更新 更多