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

在课堂上不使用链式承诺

  •  1
  • tic  · 技术社区  · 6 年前

    这是一个更大问题的一部分,但是当类需要 promise 解析以获取数据。

    以下操作将不起作用 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
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   tic    6 年前

    您只需重新分配 then (这是另一个承诺) 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
      
        2
  •  0
  •   Daniel A. White    6 年前

    我会避免重新分配 this.promise

    如果你想避免使用 .then ,看使用 async / await