我有一堆代码。该代码具有异步功能,即 Promise。我在 try...catch 里等待我的 promise 。如果有错误,我会真诚地拒绝。看到这个,
runService(options.target, options, socket)
.then(async id => {
if(user) {
.
.
.
})
.catch(error => {
console.log('Here', error);
return socket.emit('error', error);
});
runService 的功能如下,
const startService = (target, options, socket) => {
return new Promise(async (resolve, reject) => {
target = typeof(target) == 'string' && target.trim() != '' ? target.trim() : false;
if(target) {
try {
let addresses = await dns.promises.lookup(url.parse(target).hostname, 4);
} catch(exception) {
return reject(exception);
}
const id = await createHash(32);
const targetSlug = url.parse(target).hostname.split('www.').reverse()[0].replace(/[-.]/g, '');
const date = new Date();
socket.emit('log', { stage: 1, message: 'Starting simulation and analysis process' });
const chrome = await launchChrome([
`--window-size=${options.fullscan ? 1920 : options.desktopResolution.width},${options.fullscan ? 1080 : options.desktopResolution.height}`,
'--disable-background-networking',
'--disable-sync',
'--disable-default-apps',
'--no-first-run',
'--enable-automation',
'--disable-translate',
'--disable-extensions',
'--mute-audio',
'--no-sandbox',
headless ? '--headless' : ''
]);
.
.
.
});
};
我正在使用 try...catch 并调用该函数,因为它会准确地抛出异常,
let addresses = await dns.promises.lookup(url.parse(target).hostname, 4);
它抛出并 UnhandledPromiseRejectionWarning
输出是这样的;
Output http://prntscr.com/mf60hr
为什么会有UnhandledPromiseRejectionWarning
它不会调用 socket.emit('error', error)
上线.catch()
堵塞。这是为什么?
最佳答案
避免 Promise
constructor antipattern ,和never pass an async function
as the executor to new Promise
!你应该只写
async function startService(target, options, socket) => {
target = typeof(target) == 'string' && target.trim() != '' ? target.trim() : false;
if(target) {
// try {
let addresses = await dns.promises.lookup(url.parse(target).hostname, 4);
// } catch(exception) {
// throw exception;
// }
// well this `try`/`catch` is pointless, just drop it
const id = await createHash(32);
const targetSlug = url.parse(target).hostname.split('www.').reverse()[0].replace(/[-.]/g, '');
const date = new Date();
socket.emit('log', { stage: 1, message: 'Starting simulation and analysis process' });
…
}
}
关于javascript - 我使用 .catch 来捕获 promise 的拒绝,但它说我使用 .catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54477531/