2017-10-16 29 views
0

我有一個承諾鏈中簡化啓動一個承諾鏈是這樣的:有條件地從一個特定的承諾

readDB(file) 
.then(parseQuery) 
    .catch((err) => console.error(err)) 
.then(selectRandom) 
    .catch((err) => console.error(err)) 
.then(requestTrailer) 
    .catch((err) => { 
    if(err == 'Got error: No results found') { 
     throw new Error(err); 
    } 
    }) 
    .then(renderMovie) 
     .catch((err) => console.error(err)); 

基本上我讀從文件的電影列表,並通過周圍的他們,讓我可以爲電影找到預告片。我wan't做的是錯誤的情況下,重複的承諾鏈從selectRandom上開始,而不必readDBparseQuery

現在我有一個工作的代碼,但它定義的鏈兩次:

//I wrap the second round of promises in a function 
selectMovie(){ 
    selectRandom(movies) 
     .then(requestTrailer) 
      .catch((err) => { 
       if(err == 'Got error: No results found') { 
        selectMovie(); //Start the function again 
        throw new Error(err); 
       } 
      }) 
      .then(renderMovie) 
      .catch((err) => console.error(err)); 
} 

//Now start the promise chain 
readDB(file) 
.then(parseQuery) 
    .catch((err) => console.error(err)) 
.then(selectRandom) 
    .catch((err) => console.error(err)) 
.then(requestTrailer) 
    .catch((err) => { 
    if(err == 'Got error: No results found') { 
     selectMovie(); //Start second round 
     throw new Error(err); 
    } 
    }) 
    .then(renderMovie) 
     .catch((err) => console.error(err)); 

有沒有更簡單的方法來做到這一點?

+0

聽起來像你只是想幹你的代碼,但你部分做到了這一點,所以無論我誤解或你錯過了明顯的。難道你不能用'selectMovie()'替換底部的部分代碼嗎? –

+0

像readDB那麼parseQuery然後selectMovie()?應該選擇電影有返回關鍵字?還是一樣? – medicengonzo

+0

我不認爲'selectMovie()'需要一個return語句,除非你想在之後添加更多的promise鏈,但是返回_something_通常是個好主意。但是,移動它,試一試,看看會發生什麼。 –

回答

1

通過調用selectMovie()函數替換.then(selectRandom)及其後的所有內容。