Combine try/catch with async/await

As an example, I will use a dummy JSON endpoint to fetch a to-do task.

If the task is not completed, the function will throw an error. Otherwise, it will return the title of the task.

const fetchData = async () => {
        // Declaring URL to fetch
        let url = '';
        // Fetching the endpoint
        let res = await fetch(url); 
        // Getting JSON variables
        let { completed, title } = await res.json();
        // Throw error if the task is not completed
        if(!completed) throw('Not completed');
        // Return title
        return title;
        // Create alert of that error

This is a way to combine try/catch with async/await.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.