DEV Community

Minh Toan
Minh Toan

Posted on

Write better JavaScript codes

💩 codes

The Callback hell

function hell() {
    step1((result1) => {
        step2((result2) => {
           ....
        })
    })
}
Enter fullscreen mode Exit fullscreen mode

The Promise hell

hell()
.then(result => {
    handle(result)
    .then(anotherResult => {
        ...
    })
    .catch(error => {
        ...
    })
})
.catch(error => {

})
Enter fullscreen mode Exit fullscreen mode

❤️ Better codes

await step1().catch(handleError);
await step2().catch(handleError);
await step3().catch(handleError);
Enter fullscreen mode Exit fullscreen mode

😊 My style

const getData = async (url) => {
    try {
        const data = await Prosime;
        return [data, null];
    } catch(error) {
        console.log(error);
        return [null, error];
    }
}

const [data, error] = await (url);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
tccodez profile image
Tim Carey

Try catch block with async await is glorious. Good write up :)