2

$httpしたがって、結果に対して成功またはエラーを呼び出すと、$httpプロミスで呼び出され、更新されたものではなく元のものが返されることを知っています。私が本当に理解していないのは、なぜですか?

現在、次のように記述できます。

$http(config)
  .success(function(data) { console.log(data); return 1; })
  .then(function (response) { 
    var msg = 'Hey, I am the original response, not 1, ';
    msg += 'and I can run even before success is completed. ';
    msg += 'This is nearly fake chaining...';
    console.log(msg);
  });

より多くのコーディングスタイル、ここのコードをこれに置き換えない正当な理由はありますか?

// The util method has been put after the return
// just as the other $http internal methods
return decoratePromise(promise);

// Util method to add method 'success' and 'error'
// to a promise. This will spread the raw respons
function decoratePromise(p) {
  p.success = function(fn) {
    return decoratePromise(p.then(function(response) {
      return fn(response.data, response.status, response.headers, config);
    }));
  };

  p.error = function(fn) {
    return decoratePromise(p.then(null, function(response) {
      return fn(response.data, response.status, response.headers, config);
    }));
  };

  return p;
}

これらの 2 つの方法についてどう考えればよいかよくわかりません。この制限に関して、それらを使用する正当な理由はありますか?

情報をありがとう!

4

1 に答える 1

0

「意味」のために:

$http.get(...).success(function(data) { ... }).error(function(data) { ... });

この場合、$httpこれらのコールバックは互いに完全に独立しているため、各関数は元のデータを必要とします。

より多くのコーディングスタイル、ここのコードをこれに置き換えない正当な理由はありますか?

=> この独立性が壊れてしまうため、上記のコードを実行することはできません。
実際、成功がトリガーされた場合にのみエラーがトリガーされるべきだったことを意味します => 完全にナンセンスです。

上記のように明確に/明示的に、通常の「低レベル」プロミスでこの「条件付きフロー」を実行することはできません。

実際、次のようにします。

$http.get(...).then(function(data){ whenSucceed }, function(data) { whenError });

しかし、成功/エラー コードが内部で作成するものとまったく同じであることが簡単にわかります。拒否には
を、.then(null, whenError)then(data)resolve

私の意見では、どちらを使用するかは好みの問題です。

于 2014-07-09T00:48:52.923 に答える