请求帮助修复一条破碎的承诺链



这是promise链。我觉得它看起来还可以,但并没有像我希望的那样工作。我已经看了一遍,一切似乎都很正常。作为新手,我只是在.then的每个新迭代中重复poem吗?我之所以要去.catch,是因为它打印出"出了问题",我很乐意得到任何建议!


let poem = 'But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer'
const poemJudge = (poem) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(poem.length > 25){
console.log('We need to review this poem further');
resolve(poem);
} else {
reject('woah what? way too elementary');
}
}, generateRandomDelay());
});
};
const keepThinking = (resolvedPoem) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(resolvedPoem.length < 45) {
console.log('terse, but we must deliberate further');
resolve(resolvedPoem);
} else {
reject('seriously? the poem is way too long!');
}
}, generateRandomDelay())
});
};
const KeepOnThinking = (secondResolvedPoem) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if(secondResolvedPoem < 40 && secondResolvedPoem > 30) {
console.log('Nailed it')
resolve(secondResolvedPoem);
} else {
reject('you are top 50 at least')
}
}, generateRandomDelay());
});
};

poemJudge(poem)
.then((resolvedPoem) => {
return keepThinking(resolvedPoem);
})
.then((secondResolvedPoem) => {
return keepOnThinking(secondResolvedPoem);
})
.then(() => {
console.log('you have completed the poem challenge');
})
.catch(() => {
console.log('something went wrong');
});

假设您在代码中定义了generateRandomDelay方法。

当您调用reject((时,promise会失败,并被捕获在.catch块中。在这个例子中,这首诗的长度>25并且<45所以:

  1. poemJudge解决了这个问题
  2. keepThinking拒绝它
  3. 你的拦截拦截被拒

您可以通过记录捕获块中的消息(错误(来确认这一点:

poemJudge(poem)
.then((resolvedPoem) => {
return keepThinking(resolvedPoem);
})
.then((secondResolvedPoem) => {
return keepOnThinking(secondResolvedPoem);
})
.then(() => {
console.log('you have completed the poem challenge');
})
.catch(err => {
console.log(err);
});

您的控制台将打印:

我们需要进一步回顾这首诗

真的吗?这首诗太长了!

最新更新