在 class 中链式承诺而不使用 .then

Chain promises in class without using .then

这是一个更大问题的一部分,但是当 class 需要 promise 来解决以获取数据时,我如何将方法调用链接到 class。

以下将不起作用,因为每次分配 this.promise 时,函数已返回 this

class Test {
  constructor(promise) {
    this.promise = promise;
  }

  add(x) {
    this.promise.then(y => {
      this.promise = new Promise(resolve => {
        resolve(x + y);
      });
    });
    return this;
  }

  multiply(x) {
    this.promise.then(y => {
      this.promise = new Promise(resolve => {
        resolve(x * y);
      });
    });
    return this;
  }

  answer() {
    this.promise.then(x => {
      console.log(x);
    });
  }
}

function getNumber(num) {
 const promise = new Promise(resolve => {
   resolve(num);
 });
 return new Test(promise);
}

const num = getNumber(30);
num.add(20).multiply(2).answer();  // Outputs 33 instead of 100: (30 + 20) * 2

我会避免重新分配 this.promise。我不会让它成为你的 class 的成员。你应该只有你的方法 return 承诺。

如果您想避免使用 .then,请考虑使用 async/await

您可以在方法中将 then(这是另一个承诺)的结果重新分配给 this.promise。这将确保 this.promise 始终是链中的最新承诺。

class Test {
    constructor(promise) {
      this.promise = promise;
    }
  
    add(x) {
      const promise = this.promise.then(num => num + x)
      return new Test(promise);
    }
  
    multiply(x) {
      const promise = this.promise.then(num =>  x * num)
      return new Test(promise);
    }
  
    answer() {
      this.promise.then(console.log)
    }
  }
  
  function getNumber(num) {
   const promise = new Promise(resolve => {
     resolve(num);
   });
   return new Test(promise);
  }
  
  const num = getNumber(30);
  num.add(20).multiply(2).answer();  // Outputs 100: (30 + 20) * 2
  num.add(5).multiply(3).answer();  // Outputs 105: (30 + 5) * 3