我使用.catch捕获对诺言的拒绝,但是它说我使用.catch

时间:2019-02-01 10:27:04

标签: javascript node.js promise

我有一堆代码。该代码具有异步功能,即承诺。我正在尝试在try ... catch中的承诺。如果有错误,我将以真正的承诺予以拒绝。看到这个

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()行。为什么会这样?

2 个答案:

答案 0 :(得分:1)

runService中,您应该将代码包装为:

let addresses...

一直到结束:

const chrome = await launchChrome([try...catch块中。


当前,您在await之外有以下try...catch个呼叫:

const id = await createHash(32);

const chrome = await launchChrome([...

如果其中任何一个错误,将不会发现该错误。

答案 1 :(得分:1)

避免使用Promise constructor antipatternnever 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' });
        …
    }
}