【问题标题】:How to use promise hierarchy while avoiding anti pattern?如何在避免反模式的同时使用承诺层次结构?
【发布时间】:2023-03-30 01:05:01
【问题描述】:

我试图学习如何避免这里描述的反模式What is the explicit promise construction antipattern and how do I avoid it?

我从 JSFiddle 上的一些代码开始,但它没有输出我所期望的..

function sum1(x){
    return new Promise(resolve => x+1)
}

function sum2(x){
  return sum1(x)
  .then(x => x+1);
}

function sum3(x){
  return sum2(x)
  .then(x => x+1)
}

sum3(1)
.then(console.log);

我希望它打印 4 但它什么也没打印

【问题讨论】:

    标签: javascript ecmascript-6 es6-promise


    【解决方案1】:

    您需要使用Promise.resolve() 创建一个已解决的承诺:

    function sum1(x){
        return Promise.resolve(x+1)
    }
    
    function sum2(x){
      return sum1(x)
      .then(x => x+1);
    }
    
    function sum3(x){
      return sum2(x)
      .then(x => x+1)
    }
    
    sum3(1)
    .then(console.log);

    【讨论】:

      【解决方案2】:

      你在 sum1 中做错了。 new Promise((resolve, reject) => {//code here}) 以函数为参数

      function sum1(x){
          return new Promise((resolve) => {
          	resolve(x + 1);
          })
      }
      
      function sum2(x){
        return sum1(x)
        .then(x => x+1);
      }
      
      function sum3(x){
        return sum2(x)
        .then(x => x+1)
      }
      
      sum3(1)
      .then(res => console.log(res));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-16
        • 1970-01-01
        • 2011-01-22
        • 1970-01-01
        • 2015-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多