【发布时间】:2019-11-05 06:56:09
【问题描述】:
当以下代码错误(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
【问题讨论】:
-
当拒绝被记录时,它到底指向哪里?在拒绝之前是否记录了任何错误?
-
我会尝试stackoverflow.com/a/46964348/1026 或进一步减少:是什么让您认为未处理的拒绝承诺是从
ping()返回的承诺?消息中没有任何地方这么说。 -
使用
--trace-warnings,它可能会显示更多信息。 -
首先更改为
const webResult = await httpsGet(urls[0]);和const pingResult = await ping('8.8.8.8');,然后去掉中间的promise 变量和重复的try/catches(实际上不需要)。可能是解释器没有意识到您在代码后面处理拒绝。 -
@jfriend00 这就是我最初发生这种情况时的样子。
标签: javascript node.js promise