ネスティングの代案として私の約束事を平坦化するのに少し問題があります。promise chainを平坦化し、エラー固有のcatch文を実行します。
ユーザーを取得し、そのIDを使用して別のテーブルの関連するポストを取得することによってテーブル結合を行いたいとします。そのようです。
User.get(uid)
.then(usr => {
return Post.get(usr.id)
})
.then(posts => {
//send posts or continue the promise chain
});
ここで問題は、特定の約束に固有のエラー処理ロジックを実行し、他に何も実行しない場合に発生します。私の例では、DBがそのIDを持つユーザーを見つけられなかった場合、エラーをスローし、指定された外部キーによって投稿を見つけられなかった場合、エラーもスローされます。私は何をしたいのようなエラー特定のメッセージで応答することである「ユーザ見つかりませんでした」または「ポストは、ユーザー与え見つからなかった」など
私はこの
User.get(uid)
.catch(e => {
//This executes whenever a user is not found but the problem is that it also
//executes the following 'then' statement
})
.then(usr => {
return Post.get(usr.id)
})
.then(posts => {
//send posts or continue the promise chain
})
.catch(e => {
//This should only execute when posts aren't found with the id
});
を実行しようとしました今度は、エラーに関係なく.then
が実行されるため、前のコードは機能しませんでした。
だから私はこの
User.get(uid)
.then(usr => {
return Post.get(usr.id)
})
.then(posts => {
//send posts or continue the promise chain
})
.catch(e => {
//This executes whenever a user is not found but the problem is that it also
//executes the following 'then' statement
})
.catch(e => {
//This should only execute when posts aren't found with the id
});
のように、catch文の後に、すべての.then文の削除について考えた。しかし最初の.catch文は常に実行するので、これは動作しません。これは私のコードは、問題の核心がある
try
{
var user = getUser(id);
try
{
var posts = getPosts(user.id);
}
catch(e)
{
//this executes only if posts aren't found
}
}
catch (e)
{
//this executes if the error originates from obtaining a user
}
'then'は' promise.then(onFulfilled、onRejected) 'という2つの引数を受け入れます。 [promiseチェーンの複数のキャッチを処理する](http://stackoverflow.com/a/26077868/6445533) – ftor
@ftor yeaしかし、私が読んだことは、これを行うための少しの反パターンと考えられます。私は正しい答えを得ることができない場合は、このオプションに頼らなければならないでしょう。 –
分岐を除いてです。 – ftor