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.
javascriptconst fetchData = async () => { try{ // Declaring URL to fetch let url = 'https://jsonplaceholder.typicode.com/todos/1'; // 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; } catch(err){ // Create alert of that error alert(err); } }
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.