2013-03-20 6 views
6

jQuery 1.9.1の約束事に問題があります。条件付きのロジックが必要になる可能性があり、それを処理する方法がわかりません。これは私の最善の試みでしたが、コメントが下に示すように、私がelseブランチにヒットしたとき、私はまだ2番目の.then()関数をヒットしました。どのようにこのようなシナリオを処理するための任意のパターン?Promisesで分岐を処理する

storage.provision(c) 

.then(function(rc){ 
    if(rc === 0){ 
     storage.write(c); 
    }else{ 
     return options.onSuccess(rc); //how i got back to the users callbacks/promise, but this 
     //takes me to the .then below 
    } 
}) 
//storage.write returns a promise as well, do I do another .then 
// like this? 
.then(function(rc){ 
    //I was hoping this would catch, the storage.write() case, and it does, but it also catches 
    //the retun options.onSuccess(rc) in the else case. 
    options.onSuccess(rc); 
}) 


.fail(function(e){ 
    //handle error using .reject() 
}); 
+0

この投稿はあなたに役立つかもしれません:http://stackoverflow.com/questions/12149993/attempting-to-break-jquery-promise-chain-with-then-fail-and-reject – mattytommo

+0

[この投稿](http: //net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/)は、より良い約束を理解するのに役立ちます。一般的に、条件文を使用する場合は、約束事を変数として保存し、条件文の中で '成功'または '失敗'を実行する必要があります。 – acconrad

答えて

4

これはoptions.onSuccess(rc);は決して最初の二.then()に無条件に実行されるという見解を取ることによって容易になります。

したがって、最初.then()いずれかrcに通過しなければならない:

  • rc === 0場合、
  • 又は直ちにrc !== 0場合を完了storage.write(c)に応じ。

.then()それは自然にそのdoneコールバックから返される新しい約束の値のいずれかを可能にするため、このために本当に便利です。

storage.provision(c).then(function(rc) { 
    if(rc === 0) { 
     var dfrd = $.Deferred(); 
     storage.write(c).done(function() { 
      dfrd.resolve(rc); 
     }).fail(dfrd.fail); 
     return dfrd.promise(); 
    } else { 
     return rc;//pass on rc to the second .then() 
    } 
}).then(function(rc){ 
    options.onSuccess(rc); 
}).fail(function(e){ 
    //handle error using .reject() 
}); 

他のアプローチが存在すると確信していますが、これはあなたのオリジナルコンセプトに最も近いと思います。

ときrc === 0新しい繰延を作成する必要がないようにいいだろうが、それはこのように動作するstorage.write()を変更する必要がなくなり、rcに渡すことに最も現実的なアプローチです。

関連する問題