0

I have a bunch of code. The code has async function, that is promise. I'm awaiting my promise inside try...catch. If there is an error, I reject it with real promise. See this,

runService(options.target, options, socket)
    .then(async id => {
        if(user) {
            .
            .
            .
    })
    .catch(error => {
        console.log('Here', error);
        return socket.emit('error', error);
    });

The runService functions like this,

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' : ''
            ]);
    .
    .
    .
    });
};

I'm using the try...catch and i call the function for it will exactly throws an exceptions in the,

let addresses = await dns.promises.lookup(url.parse(target).hostname, 4);

It throws and UnhandledPromiseRejectionWarning and the output is this;

Output http://prntscr.com/mf60hr

Why there is an UnhandledPromiseRejectionWarning and it doesn't call the socket.emit('error', error) line on .catch() block. Why is this?

M. Çağlar TUFAN
  • 626
  • 1
  • 7
  • 21

2 Answers2

1

In runService, you should wrap the code starting from:

let addresses...

all the way to the end of:

const chrome = await launchChrome([ in the try...catch block.


Currently, you have the following await calls outside of your try...catch:

const id = await createHash(32);

const chrome = await launchChrome([...

If any of them errors, the error will not be caught.

Excellence Ilesanmi
  • 3,295
  • 1
  • 18
  • 17
1

Avoid the Promise constructor antipattern, and never pass an async function as the executor to new Promise! You should be writing just

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' });
        …
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • How I will reject or resolve the result of this async function? Because in my implemention, I have so much lines of code and Im returning results with resolve or reject? Thanks again :) – M. Çağlar TUFAN Feb 01 '19 at 10:51
  • So I should to use `return` keyword to `reject` or `resolve` yea? – M. Çağlar TUFAN Feb 01 '19 at 10:55
  • 1
    Yep, I agree with @Bergi, an async function always returns a promise. See this illustration: https://gist.github.com/lon-io/f8594f0fb40a555549f3e94f2866dae5 – Excellence Ilesanmi Feb 01 '19 at 10:56
  • Oh my godness! What an expression is this? I will save this to my important things pool :) Thanks @ExcellenceIlesanmi – M. Çağlar TUFAN Feb 01 '19 at 10:58
  • 1
    @MuhammedÇağlarTUFAN Yes, that's how `async function`s work. – Bergi Feb 01 '19 at 11:01
  • Ehmm :P I did replace every `resolve()` and `reject()` to `return`. Removed `return new Promise((resolve, reject) => {...})` expression on `startService` function and, I did `const startService = (target, options, socket) => {...}` to `async function startService(target, options, socket)` but It did output the samething :/ – M. Çağlar TUFAN Feb 01 '19 at 11:06
  • 1
    @MuhammedÇağlarTUFAN Maybe there are more mistakes in the code that you left out? Notice that of course you cannot `return` from a callback. – Bergi Feb 01 '19 at 11:07
  • @Bergi, can you inspect my imlementation please? https://jsfiddle.net/wa0er7d4/1/ – M. Çağlar TUFAN Feb 01 '19 at 11:11
  • 1
    @MuhammedÇağlarTUFAN Much too much too much code in a single method so I won't go into detail, but there are many promises which you seem to simply ignore. [Don't mix `await` with `.then(…)` syntax](https://stackoverflow.com/a/54387912/1048572)! You should be doing `const results = await Promise.all(promises)` for example. Don't pass `async function`s as `then` callbacks! – Bergi Feb 01 '19 at 11:24
  • Alright, @Bergi , thanks for your helps. I have a little, theoric question about this. If I don't use `.then().catch()` in anywhere of a async function, how can I catch the errors? How can I know the result of this `await (async function)` is expected result or not expected (error) result? – M. Çağlar TUFAN Feb 01 '19 at 11:34
  • 1
    See https://stackoverflow.com/questions/44663864/correct-try-catch-syntax-using-async-await. notice there's a difference between handling errors of `await`ed promises *inside* an `async function` vs handling errors on the result of calling an `async functon` (which is just a normal promise) – Bergi Feb 01 '19 at 11:37
  • Yea, im on it. Thanks @Bergi for your time. I wanted to upvote all your responses and other guy's too but im under 15 reputations :/ – M. Çağlar TUFAN Feb 01 '19 at 11:44
  • Ops, same to me. Im so sorry, but when I got up +15 reputations i will tick +1 your all comments with answer, you can trust me. Thanks so much. – M. Çağlar TUFAN Feb 01 '19 at 12:05