如何跳过一个链条的承诺

我在一个nodejs项目中工作,并希望跳过链中的承诺。 以下是我的代码。 在第一个promise块中,它将parsing一个值{success: true} 。 在第二部分,我想检查success的价值,如果是真的,我想把价值返回给被调用,并跳过这个链中的其余承诺; 而如果价值是假的,则继续连锁。 我知道我可以抛出一个错误或拒绝它在第二块,但我必须处理错误的情况下,这不是一个错误的情况下。 那么我怎么能在诺言链中实现呢? 我需要一个解决scheme,不带任何其他第三方库。

 new Promise((resolve, reject)=>{ resolve({success:true}); }).then((value)=>{ console.log('second block:', value); if(value.success){ //skip the rest of promise in this chain and return the value to caller return value; }else{ //do something else and continue next promise } }).then((value)=>{ console.log('3rd block:', value); }); 

简单地嵌套你想要跳过的部分链(在你的情况下的剩余部分):

 new Promise(resolve => resolve({success:true})) .then(value => { console.log('second block:', value); if (value.success) { //skip the rest of this chain and return the value to caller return value; } //do something else and continue return somethingElse().then(value => { console.log('3rd block:', value); return value; }); }).then(value => { //The caller's chain would continue here whether 3rd block is skipped or not console.log('final block:', value); return value; }); 

如果你不喜欢嵌套的想法,你可以把你的链的其余部分分解成一个单独的函数:

 // give this a more meaningful name function theRestOfThePromiseChain(inputValue) { //do something else and continue next promise console.log('3rd block:', value); return nextStepIntheProcess() .then(() => { ... }); } function originalFunctionThatContainsThePromise() { return Promise.resolve({success:true}) .then((value)=>{ console.log('second block:', value); if(value.success){ //skip the rest of promise in this chain and return the value to caller return value; } return theRestOfThePromiseChain(value); }); } 

除此之外,在中游并没有真正的办法阻止诺言。