2017-08-08 24 views
0

我有一種情況,我想處理多個承諾。跳過承諾之一,如果變量未定義

假設我有3變量

fileOption, setupOptions, moveOption 

每個變量的基礎,我請求的功能,如

file.validate(token) 
    .then((token) => file.create(fileOption)) 
    .then((file) => setup ? file.getToken(userfromSetup) : Promise.resolve({})) 
    .then((token) => setup ? file.setup(setupOptions) : Promise.resolve({})) 
    .then((data) => moveOption ? file.getTokenForMove(userFromMove) : Promise.resolve({})) 
    .then((token) => moveOption ? file.move(moveOption) : Promise.resolve({})) 
    .then((success)=>logger.log(`file created successfully`)) 
    .catch((err)=>logger.error(`Error`)) 

如果setupOption是不確定的話,我不希望得到令牌它和創建文件的設置和moveOption相同。爲了創建一個安裝程序,我需要創建令牌第一,同爲移動

所以我關心的是如何跳過的承諾和不必要的空話回報,如果上述變量是不確定

+0

我會在你開始做任何承諾之前檢查null。然後,您可以根據自己的喜好定製代碼。 – Webbanditten

+0

這就是所謂的「承諾鏈」。如果'setupOption'如果在鏈外定義,就像這裏似乎是這種情況,那麼爲什麼即使開始承諾而不先檢查它呢? – guessimtoolate

+0

所有變量都是動態內容。他們會在運行時。這就是爲什麼我檢查了承諾。 – Sam

回答

0
var file_promise = file.validate(token) 
.then((token) => file.create(fileOption)) 
.then((file) => setup ? file.getToken(userfromSetup) : Promise.resolve({})) 
.then((token) => setup ? file.setup(setupOptions) : Promise.resolve({})); 
if(moveOption){ 
    file_promise.then((data)=>{file.getTokenForMove(userFromMove)}); 
} 
file_promise.then((token) => moveOption ? file.move(moveOption) : Promise.resolve({})) 
.then((success)=>logger.log(`file created successfully`)) 
.catch((err)=>logger.error(`Error`)); 

你可以只需使用一個變量,並使用常規條件語句來鏈接或不鏈接承諾。

可能由此產生的問題是,每個步驟都不能確定它會接收什麼,但是你的代碼爲then()中調用的函數創建了參數,但是它們不使用它們,所以它不應該導致任何麻煩。否則,你會像你一樣做,並用默認值或其他東西解決。