skip to Main Content
async function fetchData() {
    const [error, response] = await fetch('https://jsonplaceholder.typicode.com/todos/1')
    if (error) {
        console.log(error);
        return
    }
    
    const [e, data] = await response.json()
    if (e) {
        console.log(e);
        return
    }
    return data
}

fetchData()

I came across a LinkedIn post showing this it the new way to represents async/await without using try-catch block, is this right correct me if its wrong. its not working for me.

2

Answers


  1. I’ve been using this workaround to avoid try/catch its like error first callback, but it make sense to use try/catch.

    async function fetchData() {
      const { error, data } = await fetch(
        "https://jsonplaceholder.typicode.com/todos/1"
      )
        .then(async (res) => {
          const data = await res.json();
          return {
            data,
            error: null,
          };
        })
        .catch((error) => ({
          error,
          data: null,
        }));
      if (error) {
        return;
      }
      return data;
    }
    
    fetchData().then(console.log);
    Login or Signup to reply.
    1. use .catch like this:
    const { error, data } = await fetch(
      "https://jsonplaceholder.typicode.com/todos/1"
    ).catch(e => {
     console.log(e);
    })
    
    1. Try a third-party library named await-to-js
    import to from 'await-to-js';
    async function fetchData() {
        const [error, response] = await to(fetch('https://jsonplaceholder.typicode.com/todos/1'))
        if (error) {
            console.log(error);
            return
        }
        
        const [e, data] = await to(response.json())
        if (e) {
            console.log(e);
            return
        }
        return data
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search