来自NodeJS的神秘未处理的承诺警告

时间:2019-06-23 00:22:41

标签: javascript node.js promise

当以下代码错误(ping()拒绝其承诺)时,我得到了警告。 HTTP函数似乎出错了。我想ping()本身必须发生某种情况,这在某种程度上避免了try-catch。

有人可以启发我吗? (这是经过几次尝试以使其正常工作的尝试。)

(async () => {
    try {
            let webTask, pingTask;

            try {
                    webTask = httpsGet(urls[0]);
            } catch (e) {
                    console.log(e);
            }

            try {
                    pingTask = ping('8.8.8.8');
            } catch (e) {
                    console.log(e);
            }

            try {
                    const webResult = await webTask;
                    console.log('HTTP result:', webResult);
            } catch (e) {
                    console.log(e);
            }

            try {
                    const pingResult = await pingTask;
                    console.log('Ping result:', pingResult);
            } catch (e) {
                    console.log(e);
            }
    } catch (e) {
            console.log('Error:', e);
    }
})();

错误是:

"main.js" 137 lines, 2945 characters
(node:58299) UnhandledPromiseRejectionWarning: #<Object>
(node:58299) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:58299) [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.

这在我定义ping函数的文件中较早:

const netping = require('net-ping');
const pingSession = netping.createSession({
    retries: 0,
    timeout: 10000
});

const ping = ip => {
    return new Promise((resolve, reject) => {
            let result = { ipAddress: ip, start: new Date(Date.now()), end: null, error: null, duration_ms: -1 };

            pingSession.pingHost(ip, (error, target) => {
                    result.end = new Date(Date.now());
                    result.duration_ms = result.end - result.start;
                    if (error) {
                            result.error = error;
console.log('rejecting promise');
                            reject(result);
                    } else {
                            resolve(result);
console.log('resolving promise');
                    }
            });
    });
};

NodeJS 11.13.0

1 个答案:

答案 0 :(得分:0)

await是javascript构造,可将对诺言的拒绝转换为异常。 也就是说,await是处理拒绝的构造。

写时:

try {
    pingTask = ping('8.8.8.8');
} catch (e) {
    console.log(e);
}

这里没有await,因此没有任何东西可以将拒绝转换为异常,或者以任何方式处理拒绝。

如果您不等待就致电ping(),则需要更明确的拒绝处理。

编辑

这里是最小的复制者:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

const test = (ms, msg) => {
    return new Promise((resolve, reject) => {
        sleep(ms).then(reject(msg)).catch(console.log);
    });
};

(async () => {
    let task1;

    try {
        const ms = 50;
        task1 = test(ms, "hey");
        await sleep(ms * 2); // otherwise you don't get an error
        await task1;
    } catch (e) {
        console.log(e);
    }
})().then(console.log).catch(console.log);
  

(节点:12822)UnhandledPromiseRejection警告:嘿(节点:12822)   UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个   由抛出异步函数引起的错误   没有障碍,或者拒绝了没有处理的承诺   使用.catch()。 (拒绝ID:1)(节点:12822)[DEP0018]   DeprecationWarning:已弃用未处理的承诺拒绝。在   未来,未处理的承诺拒绝将终止   使用非零退出代码的Node.js进程。嘿undefined(node:12822)   PromiseRejectionHandledWarning:已处理承诺拒绝   异步(拒绝ID:1)

Promise()构造函数开始运行test(),在50毫秒后,承诺被拒绝,但是没有没有将拒绝转换为异常。 如果我们删除了100 ms的睡眠,则await在完成50 ms睡眠之前将其“将异常转换为异常”逻辑注册到promise方式中,因此当{{1} },其中有一个将其转换为异常的处理程序。