即使被拒绝的承诺得到处理,也会收到`UnhandledPromiseRejectionWarning`

时间:2016-12-04 21:08:29

标签: javascript node.js runtime-error generator es6-promise

我构建了一个函数,它遍历包含同步代码和Generator的{​​{1}}:

Promises

现在,当我使用此代码导入并运行它时:

module.exports = {


    isPromise (value) {
            return typeof value === 'object' && value !== null && 'then' in value;
        },

    runGen (generatorFunc, startValue) {

            let that = this,
                i = 0;

            function *iterator(resolve, reject) {

                let runGeneratorFunc = generatorFunc(startValue),
                    yieldedOut = {done: false},
                    yieldIn;

                while (!yieldedOut.done) {
                    console.log(i++, 'Ready for next iteration');
                    if (that.isPromise(yieldedOut.value)) {
                        console.log(i++, 'Pass promise to KeepIterating');
                        yieldIn = yield yieldedOut.value;
                        console.log(i++, 'Received value from promise');

                        if(yieldIn instanceof Error){
                            console.log(i++, 'Value was instance of Error');
                            try {
                                yieldedOut = runGeneratorFunc.throw(yieldIn)
                            }
                            catch(err){
                                console.log(i++, 'Throw Error');
                                throw(yieldIn);
                            }
                        } else {
                            yieldedOut = runGeneratorFunc.next(yieldIn);
                        }
                    } else {
                        try {
                            yieldIn = yieldedOut.value;
                            yieldedOut = runGeneratorFunc.next(yieldIn);
                        }
                        catch(err) {
                            runGeneratorFunc.throw(err);
                            reject(err);
                        }
                    }
                }
                resolve(yieldedOut.value);
            }

            return new Promise(function (resolve, reject) {
                var runIterator = iterator(resolve, reject);
                (function keepIterating(yieldIn) {
                    let yieldedOutPromise = runIterator.next(yieldIn);

                    if (!yieldedOutPromise.done) {

                        yieldedOutPromise.value.then(function (fulfilledValue) {
                            console.log('never gets here');
                            keepIterating(fulfilledValue);
                        });

                        yieldedOutPromise.value.catch(function (err) {
                            console.log(i++, 'Rejected promise catched');
                            if (err instanceof Error) {
                                try {
                                    console.log(i++, 'Rejected promise is instance of Error');
                                    let yieldedOut = runIterator.next(err);
                                    keepIterating(yieldedOut);
                                }
                                catch (err) {
                                    console.log(i++, 'Error propagated back out');
                                    yieldedOutPromise.value.catch(() => {})
                                    reject(err);
                                }
                            } else {
                                try {
                                    let yieldedOut = runIterator.next(new Error(err));
                                    keepIterating(yieldedOut);
                                }
                                catch (err) {
                                    reject(err);
                                }
                            }
                        })
                    }
                })();
            });
        }
    }

我将此记录到控制台:

const md = require('./module');

function* dummy () {
    yield Promise.reject(new Error('error1'));
}

md.runGen(dummy)
.catch(err => {
    console.log(9, 'Finished!');
})

除了0 'Ready for next iteration' 1 'Ready for next iteration' 2 'Promise yielded out' 3 'Rejected promise handled' 4 'Rejected promise instance of Error' 5 'Ready to handle promise value' 6 'Value was instance of Error' 7 'Throw Error' 8 'Error propagated back out' 9 'Finished!' (node:9904) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: error1 (node:9904) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 的警告外,这一切都符合预期。我很困惑为什么我会收到此警告,因为据我所知,在代码中处理了被拒绝的UnhandledPromiseRejectionWarning

我在俯瞰什么?

1 个答案:

答案 0 :(得分:2)

  

我在俯瞰什么?

您的yieldedOutPromise.value.then来电正在创建新承诺,如果yieldedOutPromise.value拒绝,那么它也会被拒绝。您通过.catch上的yieldedOutPromise.value来处理错误并不重要,但仍有一个被拒绝的承诺,而且它将被报告。

您基本上是在拆分您的保证链,这导致每个端都需要一个错误处理程序。但是,你根本不应该分裂任何东西。而不是

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

反模式你应该使用

promise.then(onSuccess, onError).…

哦,当你在它的时候,avoid the Promise constructor antipattern。只是做

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