2016-04-28 98 views
3

使用嵌套承諾編寫乾淨的代碼的正確策略是什麼?使用承諾背後的想法之一是擺脫嵌套回調,也叫callback hell。即使使用的承諾時,嵌套似乎是不可避免的,有時:乾淨的代碼和嵌套承諾

User.find({hande: 'maxpane'}) 
    .then((user) => { 
    Video.find({handle: user.handle}) 
    .then((videos) => { 
     Comment.find({videoId: videos[0].id}) 
     .then((commentThead) => { 
      //do some processing with commentThread, vidoes and user 
     }) 
    }) 
    }) 

有擺脫嵌套,使代碼更「線性」的方式。實際上,這段代碼與使用回調的代碼看起來並沒有太大的區別。

+2

似乎[這個答案](http://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-thenchain)可能是一個很好的閱讀你,如果不是重複的。 – CodingIntrigue

回答

4

使用承諾的最大優勢在於鏈接。這是你應該如何正確地使用它:

User.find({handle: 'maxpane'}) 
.then((user) => { 
    return Video.find({handle: user.handle}) 
}) 
.then((videos) => { 
    return Comment.find({videoId: videos[0].id}) 
}) 
.then((commentThead) => { 
    //do some processing with commentThread, vidoes and user 
}) 

每次返回無極裏面的.then它作爲承諾在未來.then回調。

+2

在最終函數中有'commentThread','videos'和'user'變量可用,在我看來,只有commentThread在函數的範圍內。 –