8

「これらのことはすべて実行しますが、いずれかが失敗した場合は保釈します」と言う良い方法を見つけようとしています。

私が今持っているもの:

var defer = $q.defer();

this
    .load( thingy ) // returns a promise

    .then( this.doSomethingA.bind( this ) )
    .then( this.doSomethingB.bind( this ) )
    .then( this.doSomethingC.bind( this ) )
    .then( this.doSomethingD.bind( this ) )

    .then( function(){
        defer.resolve( this );
    } );
    ;

return defer.promise;

私が最終的に望んでいるのは、そのチェーンのエラーを何らかの方法でキャッチして、defer上記のプロミスに渡すことができるようにすることです。構文が上記のものと同様に維持されているかどうかは特に気にしません。

または、誰かが上記のチェーンを停止する方法を教えてくれても.

4

6 に答える 6

6

then コールバック内で拒否された promise を返すことで、angularjs チェーンを停止できます。

load()
.then(doA)
.then(doB)
.then(doC)
.then(doD);

doA 、doBdoCdoDは次のようなロジックを持つことができます

var doA = function() {
    if(shouldFail) {
        return $q.reject();
    }
}
于 2015-07-20T19:01:18.477 に答える
3

私はこれに出くわし、これらすべての答えがひどく時代遅れであることに気付きました. たまたまこの投稿を見つけた人のために、これを処理する適切な方法を次に示します。

// Older code
return this.load(thing)
  .then(this.doA, $q.reject)
  .then(this.doB, $q.reject)
  .then(this.doC, $q.reject)
  .then(this.doD, $q.reject)
  .then(null, $q.reject);


// Updated code
// Returns the final promise with the success handlers and a unified error handler
return this.load(thing)
  .then(this.doA)
  .then(this.doB)
  .then(this.doC)
  .then(this.doD)
  .catch(this.handleErrors); // Alternatively, this can be left off if you just need to reject the promise since the promise is already rejected.
  // `.catch` is an alias for `.then(null, this.handleErrors);`
于 2015-07-29T06:55:20.187 に答える
2

次の方法で同じことができるはずです。

var defer = $q.defer();

this
    .load( thingy ) // returns a promise

    .then( this.doSomethingA.bind( this ), $q.reject )
    .then( this.doSomethingB.bind( this ), $q.reject )
    .then( this.doSomethingC.bind( this ), $q.reject )
    .then( this.doSomethingD.bind( this ), $q.reject )

    .then( defer.resolve.bind( defer, this ), defer.reject.bind( defer ) );
    ;

return defer.promise;
于 2013-10-23T17:59:28.180 に答える
0

このユースケースは予想され、 $q.reject(reason) を使用して対処されたようです

于 2013-10-23T15:58:36.243 に答える