2015-06-16 5 views
3

Я использую Bluebird Promises для приложения Node.js. Как я могу ввести условные ветви цепочки для моего приложения? Пример:Bluebird Promise: Вложенные или условные цепочки

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

Кроме того, не выяснял рабочую версию этого же, это решение чувствует (и выглядит) странно как-то. У меня есть подозрительное подозрение, что я несколько нарушаю концепцию обещаний или что-то в этом роде. Любые другие предложения о том, как ввести такой условный ветвление (каждый из которых отличается не одним, а многими последующими шагами)?

+0

Смотрите также [вложенный] (http://stackoverflow.com/a/22000931/1048572) и [условный] (http://stackoverflow.com/q/26599798/1048572) цепи в целом – Bergi

ответ

4

Да, вы можете это сделать, просто так. Важно только всегда return обещание от ваших функций (обратного вызова).

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 
}; 
0

Просто верните дополнительные обещания из вашего .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 
      }); 
    }); 
}; 
Смежные вопросы