Receiving `UnhandledPromiseRejectionWarning` even though rejected promise is handled

后端 未结 1 1602
花落未央
花落未央 2021-01-21 12:33

I have constructed a function which iterates through a Generator containing both synchronous code and Promises:

module.exports = {


           


        
相关标签:
1条回答
  • 2021-01-21 13:09

    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);
            }
        });
    };
    
    0 讨论(0)
提交回复
热议问题