6

jQuery 1.9.1 のプロミスに問題があり、別の遅延を返す条件付きロジックが必要になる可能性があり、それを処理する方法がわかりません。これは私の最善の試みでしたが、以下のコメントが示すように、else ブランチをヒットしたときに、まだ 2 番目の .then() 関数をヒットしており、そこでユーザーに戻れることを望んでいます。そのようなシナリオを処理する方法のパターンはありますか?

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()
});
4

1 に答える 1

4

options.onSuccess(rc);これは、2 番目のビューでは無条件に実行され、1 番目のビューでは実行されないビューを使用することで簡単になり.then()ます。

したがって、最初は次のいずれか.then()を渡す必要があります。rc

  • if 、完了rc === 0に応答してstorage.write(c)
  • またはすぐにrc !== 0

.then()doneコールバックから新しい Promise の値を返すことが自然に許可されるため、これには非常に便利です。

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()
});

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

新しい Deferred when を作成する必要がないのは良いことですが、このように動作するように変更する必要がなく、rc === 0を渡すのが最も現実的なアプローチです。rcstorage.write()

于 2013-03-21T00:10:57.417 に答える