Receiving `UnhandledPromiseRejectionWarning` even though rejected promise is handled

两盒软妹~` 提交于 2019-12-02 00:54:47
Bergi

What am I overlooking?

Your yieldedOutPromise.value.then call is creating a new promise, and if yieldedOutPromise.value rejects then it will be rejected as well. It doesn't matter that you handle the error via .catch on yieldedOutPromise.value, there's still a rejected promise around, and it's the one that will be reported.

You are basically splitting your promise chain, which leads to each end needing an error handler. However, you shouldn't be splitting anything at all. Instead of the

promise.then(onSuccess);
promise.catch(onError);

antipattern you should use

promise.then(onSuccess, onError).…

Oh, and while you're at it, avoid the Promise constructor antipattern. Just do

module.exports = function runGen (generatorFunc, startValue) {
    return Promise.resolve(startValue).then(generatorFunc).then(generator => {
        return keepIterating({done: false, value: undefined});
        function keepIterating({done, value}) {
            if (done) return value;
            return Promise.resolve(value).then(fulfilledValue =>
                generator.next(fulfilledValue)
            , err =>
                generator.throw(err)
            ).then(keepIterating);
        }
    });
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!