Node Unhandled Promise问题

时间:2017-10-16 17:21:05

标签: javascript node.js promise

我之前问过这里的问题: Retaining Data across multiple promise chains

我最终使用T.J. Crowder对我的基本代码的回答并且自那以后做了很多改变。但我注意到节点中有些奇怪的东西,我似乎无法克服。我回到了他提供的基本代码,问题似乎也存在。

以下是示例:

"use strict";

// For tracking our status
class Status {
    constructor(total = 0, count = 0) {
        this.id = ++Status.id;
        this.total = total;
        this.count = count;
    }
    addCall() {
        ++this.total;
        return this;
    }
    addProgress() {
        ++this.count;
        return this;
    }
    toString() {
        return `[S${this.id}]: Total: ${this.total}, Count: ${this.count}`;
    }
}
Status.id = 0;

// The promise subclass
class RepoPromise extends Promise {
    constructor(executor) {
        super(executor);
        this.s = new Status();
    }
    // Utility method to wrap `then`/`catch` callbacks so we hook into when they're called
    _wrapCallbacks(...callbacks) {
        return callbacks.filter(c => c).map(c => value => this._handleCallback(c, value));
    }
    // Utility method for when the callback should be called: We track that we've seen
    // the call then execute the callback
    _handleCallback(callback, value) {
        this.s.addProgress();
        console.log("Progress: " + this.s);
        return callback(value);
    }
    // Standard `then`, but overridden so we track what's going on, including copying
    // our status object to the new promise before returning it
    then(onResolved, onRejected) {
        this.s.addCall();
        console.log("Added: " + this.s);
        const newPromise = super.then(...this._wrapCallbacks(onResolved, onRejected));
        newPromise.s = this.s;
        return newPromise;
    }
    // Standard `catch`, doing the same things as `then`
    catch(onRejected) {
        this.s.addCall();
        console.log("Added: " + this.s);
        const newPromise = super.catch(...this._wrapCallbacks(onRejected));
        newPromise.s = this.s;
        return newPromise;
    }
}

// Create a promise we'll resolve after a random timeout
function delayedGratification() {
    return new Promise(resolve => {
        setTimeout(_ => {
            resolve();
        }, Math.random() * 1000);
    });
}

// Run! Note we follow both kinds of paths: Chain and diverge:
const rp = RepoPromise.resolve('Test');
rp.then(function(scope) {
    return new Promise((resolve, reject) => {
        console.log('  Rejected')
        reject(scope)
    })
})
.catch(e => {console.log('Never Makes it')})

当我使用:node test.js运行时,我得到以下输出

Added: [S1]: Total: 1, Count: 0
Added: [S1]: Total: 2, Count: 0
Added: [S1]: Total: 3, Count: 0
Progress: [S1]: Total: 3, Count: 1
  Rejected
(node:29364) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Test
(node:29364) [DEP0018] 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.

请注意,"never makes it"的控制台日志不存在,请注意,我已经解决了catch运行两次的问题,因为它是then(null, function(){})的简单语法糖,所以你可以忽略那个。

为什么抓不到我想象的工作?当我以正常承诺执行此操作时,没有问题,如下所示。所以我知道_wrapCallbacks导致问题的事实,我只是不确定原因,或者如何解决它。

const rp = Promise.resolve('Test');
rp.then(function(scope) {
    return new Promise((resolve, reject) => {
        console.log('  Rejected')
        reject(scope)
    })
})
.catch(e => {console.log('Makes it')})

1 个答案:

答案 0 :(得分:1)

catch实施您的承诺并不起作用。请注意,原生catch已实施为return this.then(null, callback) - 调用super.catch只会直接返回then实施。

你的then实现有一个重大错误:它不希望在函数之前获得null参数。当您执行此操作时,请观察上述呼叫中发生的情况:

_wrapCallbacks(...callbacks) {
    return callbacks.filter(c => c).map(…);
//                  ^^^^^^^^^^^^^^^
}
then(onResolved, onRejected) {
    …
    const newPromise = super.then(...this._wrapCallbacks(onResolved, onRejected));
    …
}

只需从参数数组中删除null,然后将onrejected回调作为onfulfilled传递。您将要删除filter并在映射函数中使用三元组:

_wrapCallbacks(...callbacks) {
    return callbacks.map(c => typeof c == "function"
      ? value => this._handleCallback(c, value)
      : c);
}

您也可以放弃被覆盖的catch