VirtualWolf VirtualWolf -4 years ago 38
Javascript Question

Should async/await code be entirely contained with try block?

I've been reading up on the new async/await and have been playing around with it in Node 8. I've come across some people putting everything within the initial

try
block, and others having only the
await
and all the rest is below the try/catch. Is one better than the other? This is one of the functions in my own code in the two styles to show what I mean:

async function findCurrentInstallations() {
try {
const results = await installations.find({});

if (results.length === 0) { throw new Error('No installations registered'); }
return results;
} catch (err) {
throw err;
}
}


--

async function findCurrentInstallations() {
let results;

try {
results = await installations.find({});
} catch (err) {
throw err;
}

if (results.length === 0) { throw new Error('No installations registered'); }
return results;
}

Answer Source

There's no need for the try and catch at all in the example you provide, It's the default behavior of async functions.

Your two code fragments differ in that the throw new Error(... in the first case will be handled by the catch clause. But since the catch clause is for all practical purposes a no-op, a pass-through, it doesn't really matter.

I would write this as:

async function findCurrentInstallations() {
    const results = await installations.find({});
    if (results.length === 0) { throw new Error('No installations registered'); }
    return results;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download