DEV Community

Discussion on: Some Best Practices of Javascript for clean and better code quality...

Collapse
 
loucyx profile image
Lou Cyx

For the Parallel API Calls you don't even need async/await, you can just:

const getData = () =>
    Promise.all([fetch(), fetch(), fetch(), fetch()])
        .then(([first, second, third, fourth]) => {
            /* ... */
        })
        .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

For the Using Objects instead of Switch for event binding you forgot about the default handler, you can use ?? for it:

const eventHandler = {
    success: handleSuccess,
    error: handleError,
    pending: handlePending,
};

const handleEvent = event => eventHandler[event] ?? handleDefault;
Enter fullscreen mode Exit fullscreen mode

Also in the honorable mentions "Use async/await instead of promise callback chain". Why tho? If you do things correctly, the code stays clean:

try {
    const response = await fetch(ENDPOINT);
    const data = await response.json();
    console.log(data);
} catch (error) {
    console.error(error);
}

// vs

fetch(ENDPOINT)
    .then(response => response.json())
    .then(console.log)
    .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

I'm not saying async/await is not useful, I'm just saying that you don't need them always, and if you do things correctly, your code stays simple without that syntax sugar.

Cheers!

Collapse
 
lexlohr profile image
Alex Lohr

The last point is heavily disputed and there are a lot of opinionated people on either side.

My position is: use what fits your case best. You can also mix await promise emitter().catch(...) for extra conciseness.