【问题标题】:Callback Hell with Promises [duplicate]带有承诺的回调地狱[重复]
【发布时间】:2015-11-24 16:10:25
【问题描述】:

我使用 Promise 让自己陷入了厄运金字塔。

我有以下几点:

  • getA
  • getB
  • getC

getC 依赖于 getB(和 getA),后者依赖于 getA

所以我必须这样称呼他们

getA(param)
  .then(getB)
  .then(getC)

但是,如上所述,我需要 getA 的输出作为 getC 的参数,所以我这样做了

getA(param)
  .then(function (A) {
    getB(A)
      .then(function (B) {
        getC(A, B)
      });
  });

是的,金字塔抓住了我……我给我的家人带来了耻辱。帮助我重新获得荣誉。

【问题讨论】:

    标签: javascript callback promise


    【解决方案1】:

    我认为你可以这样做。

    var S;
    getA(param)
    .then(function (A) {
        return S = A;
    })
    .then(getB)
    .then(function (B) {
        return getC(S, B);
    })
    .then(function (C) {
        console.log(C);
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用 Promise.all 来等待多个承诺:

      你的伪代码变成:

      var pa = new Promise(function(){/*function A*/});
      var pb = new Promise(function(){
          pa.then(function {/*function B*/}
      });
      Promise.all([pa, pb]).then(function(){/*function C*/});
      

      【讨论】:

      • pa.then 之前需要一个return,否则它将不起作用。使用 Promise.all 的好主意,但 -1 表示 promise-constrictor 反模式。 getA 等已经返回承诺,因此对构造函数的需求为零。
      • 更不用说您错误地使用了 Promise 构造函数。如果不调用resolvereject,承诺将永远不会实现。
      猜你喜欢
      • 2020-12-24
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 2019-09-18
      • 2016-08-30
      • 2014-06-21
      • 2015-06-06
      • 2019-06-21
      相关资源
      最近更新 更多