【问题标题】:migrate deprecated promise-handling code迁移弃用的承诺处理代码
【发布时间】:2016-12-11 21:20:35
【问题描述】:

我有一些代码可以处理这样的 Angular 承诺

somethingThatReturnsAPromise
  .then(function (data) {
    // handle success  
  })
  .catch(function (error) {
    // handle error
  })
  .finally(function () {
    // always do this
  });

我知道这个语法现在已经被弃用了,这段代码应该被替换为

somethingThatReturnsAPromise.then(
  function (data) {
    // handle success  
  },
  function (error) {
    // handle error
  }
);

但是,当使用这种新语法时,我应该将之前在 finally 中的代码放在哪里,即在 promise 被解决(成功)和被拒绝(失败)时执行的代码?

【问题讨论】:

  • 你从哪里听到的?
  • 如果 catch 和 finally 被弃用,我会很惊讶
  • 尽管如此,catch(f) = then(null, f) and finally(f) = then (f, f)
  • .catch() 是 ES6 承诺规范的一部分。如果有人反对它,我会感到惊讶。

标签: javascript angularjs promise


【解决方案1】:

1st:我没有发现任何关于在 official docs 中被弃用的(与 Promise 相关的)方法。

第二个:finallythen(cb, cb) 复杂得多,因为它不会捕获错误,也不会传播你的回调结果,但是如果你返回一个承诺,它会等待这个承诺解决,直到它继续传播当前值。

这样的:

function _finally(promise, callback) {
    var handleValue = isError => value => $q((resolve, reject) => {
        //call your callback
        //if this throws, propagate the Error
        var w = typeof callback === "function" && callback();

        //prepare to push the current value/error
        var fn = isError?
            () => reject(value):
            () => resolve(value);

        //check wether your callback has returned sth. Promise-like
        if(w && typeof w.then === "function"){
            //then we'll wait for this to resolve, 
            //before we continue propagating the current value/error
            w.then(fn, fn);
        }else{
            //otherwise propagate the current value/error emmediately
            fn();
        }
    });

    return $q.resolve(promise).then(
        handleValue(false),
        handleValue(true)
    );
}

我编写这段代码只是为了让您了解finally 的作用。 Angular 的实现更流畅,所以坚持下去。

我认为没有任何理由认为 catchfinally 已被弃用或将永远被弃用。

【讨论】:

    【解决方案2】:

    如果您想使用then 两种方式,您可以为成功和错误承诺处理程序提供处理程序:

    function always() {
        // Do whatever either it fails or succeeds
    }
    
    somethingThatReturnsAPromise.then(always, always).then(function(data) {
    
    }, function(error) {
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多