2016-11-17 80 views
1

考虑这个代码,其中start,continuefinish是承诺。如何编写嵌套Promises

export const do =() => { 
    return new Promise((resolve, reject) => { 
     start() 
      .then(() => continue()) 
      .then(() => finish()) 
      .then(() => resolve()) 
      .catch((reason) => reject(reason)) 
    }); 
}; 

这是怎么写嵌套承诺?

+3

嗯,是的,这会奏效。但是,只要'do =()=> start()。then(continue).then(finish)'也可以,因为这已经是一个承诺,你不需要一个新的Promise。 – deceze

+2

不会将此类作为个人重复使用,但它是相关的:[什么是显式承诺构造反模式,以及如何避免它?](http://stackoverflow.com/questions/23803743/what-is-the-显式的承诺 - 建设 - 反模式和如何-DO-I-避免-IT) –

回答

1

只返回整条产业链,没有必要把它包起来:

export const _do =() => start() 
      .then(continue) 
      .then(finish) 
;