2016-11-17 88 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) 
;