2017-08-08 23 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()中调用的函数创建了参数,但是它们不使用它们,所以它不应该导致任何麻烦。否则,你会像你一样做,并用默认值或其他东西解决。