Обещание Синей птицы: вложенные или условные цепочки
Я использую Bluebird Promises для узла.приложение js. Как я могу ввести условные ветви цепочки для моего приложения? Пример:
exports.SomeMethod = function(req, res) {
        library1.step1(param) 
        .then(function(response) { 
            //foo
            library2.step2(param)
            .then(function(response2) { //-> value of response2 decides over a series of subsequent actions
                if (response2 == "option1") {
                    //enter nested promise chain here?
                    //do().then().then() ...
                }
                if (response2 == "option2") {
                    //enter different nested promise chain here?
                    //do().then().then() ...
                }
               [...]
            }).catch(function(e) { 
                //foo
            });
    });
};
Помимо того, что я еще не придумал рабочую версию этого, это решение кажется (и выглядит) странным. У меня появилось тайное подозрение, что я несколько нарушаю концепцию обещаний или что-то в этом роде. Любые другие предложения, как ввести этот вид условного ветвления (каждый из которых включает не один, а много последующих шаги)?
2 ответа:
Да, вы можете сделать это, просто так. Важно просто Всегда
returnобещание от ваших (callback) функций.exports.SomeMethod = function(req, res) { return library1.step1(param) // ^^^^^^ .then(function(response) { … foo return library2.step2(param) // ^^^^^^ .then(function(response2) { if (response2 == "option1") { // enter nested promise chain here! return do().then(…).then(…) // ^^^^^^ } else if (response2 == "option2") { // enter different nested promise chain here! return do().then(…).then(…) // ^^^^^^ } }).catch(function(e) { // catches error from step2() and from either conditional nested chain … }); }); // resolves with a promise for the result of either chain or from the handled error };
Просто верните дополнительные обещания из вашего обработчика
.then(), как показано ниже. Ключ состоит в том, чтобы вернуть обещание из обработчика.then(), и это автоматически связывает его с существующими обещаниями.exports.SomeMethod = function(req, res) { library1.step1(param) .then(function(response) { //foo library2.step2(param) .then(function(response2) { //-> value of response2 decides over a series of subsequent actions if (response2 == "option1") { // return additional promise to insert it into the chain return do().then(...).then(...); } else if (response2 == "option2") { // return additional promise to insert it into the chain return do2().then(...).then(...); } [...] }).catch(function(e) { //foo }); }); };