悬梁刺股

问题描述 投票:0回答:1

这是承诺链。我觉得它看起来还不错,但它没有像我想要的那样工作。我看了一遍,一切似乎都没有问题。作为一个新手,我是否只是重复 poem 在每一次新的 .then? 我正在做的 .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');
});
javascript ecmascript-6 promise es6-promise chain
1个回答
1
投票

假设你的代码中定义了方法generateRandomDelay。

当你调用reject()时,一个承诺失败了,它在一个.catch块中被捕获。在这个例子中,诗的长度是&gt;25和&lt;45所以。

  1. poemJudge解决它
  2. 思维定势
  3. 你的捕捉块捕捉到了拒绝信息。

你可以通过记录你在捕获块中得到的信息(err)来确认这一点。

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);
});

你的控制台将打印。

我们需要进一步审查这首诗

诗太长了!

© www.soinside.com 2019 - 2024. All rights reserved.