2016-06-27 10 views
4

、私は次のコードを持っている:どのように適切なチェーンはお互いに依存する約束を約束しますか?

const request = require('request-promise'); 

request(validateEmailOptions).then(function(result) { 
    if (result.valid) { 
    request(createUserOptions).then(function (response) { 
     if (response.updatePassword) { 
     request(modifyUserOptions).then(function (response) { 
      return res.redirect('/signin'); 
     }).catch(function(error) { 
      return res.redirect('/error'); 
     }); 
     } 
    }).catch(function(error) { 
     return res.redirect('/error'); 
    }); 
    } else { 
    return res.redirect('/error'); 
    } 
}) 
.catch(function (reason) { 
    return res.redirect('/error'); 
}); 

を基本的には、要求の呼び出しの連鎖、前の呼び出しの結果に基づいて、各一つです。問題は、各条件にさらに多くの行があり、その結果、コードが膨大になって読みにくくなることです。私は、要求の約束を使用してコールチェーンを書くか、単にブルーバードを要求するより良い方法があるかどうかを知りたいと思います。

+1

'!response.updatePassword'はどうなりますか?あなたは基本的に 'undefined'を返しています... – elclanrs

答えて

4

約束を取り消すことができます。私は最初のエラー状態を扱うことを意味し、できるだけ早期に失敗推薦し、意味のあるエラーメッセージを持つことがログインできるように

f(a).then(function(a) { 
    return g(b) 
}).then(function(b) { 
    return h(c) 
}) 

f(a).then(function(a) { 
    return g(b).then(function(b) { 
    return h(c) 
    }) 
}) 

と同じです:これはと思いますそれらが必要な場合。最後に、エラーを伝播して単一のキャッチで処理できます。あなたのコードの文脈でそれを置く:

request(validateEmailOptions).then(function(result) { 
    if (!result.valid) { 
    throw new Error('Result is not valid'); 
    } 
    return request(createUserOptions); 
}).then(function(response) { 
    if (!response.updatePassword) { 
    throw new Error('Password is not updated'); 
    } 
    return request(modifyUserOptions); 
}).then(function(response) { 
    return res.redirect('/signin'); 
}).catch(function(error) { 
    // you may want to log the error here 
    return res.redirect('/error'); 
}); 
関連する問題