javascript - 来自 NodeJS 的神秘未处理 promise 警告

标签 javascript node.js promise

当以下代码错误(ping()拒绝其 promise )时,我收到警告。 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

最佳答案

await是一个 javascript 构造,它将 promise 的拒绝转换为异常。 即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);

(node:12822) UnhandledPromiseRejectionWarning: hey (node:12822) 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:12822) [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. hey undefined (node:12822) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)

Promise()构造函数开始运行test() ,50 毫秒后,promise 被拒绝,但没有任何东西可以将拒绝转换为异常。 如果我们删除 100 毫秒 sleep ,则 await在 50 毫秒 sleep 完成之前将其“将拒绝转换为异常”逻辑注册到 Promise 方式上,因此当 Promise 在 await 之后约 49 毫秒被拒绝时被调用时,有一个处理程序将其转换为异常。

关于javascript - 来自 NodeJS 的神秘未处理 promise 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720110/

相关文章:

javascript - 在 Firefox 的引导模式下,Sweet Alert 中的文本框无法聚焦

javascript - 从 useReducer Hook 返回的状态是 "deep copy"还是 reducer 输出的引用?

javascript - 无法用 Angular 加载@ng-bootstrap/ng-bootstrap

javascript - javaScript 不是 DOM 的一部分吗?

Node.js 终止异步调用

mysql - Node : Insert string of special characters in mysql database

javascript - nodejs mongodb,从数据库没有得到结果

angularjs - 在 Angular 中,promise 的 error 和 catch 函数在概念上的区别是什么?

javascript - 升级 : get() requires key and callback arguments - no Promise?

JavaScript 新的 Promise 速记