0

I am using fetch and async await to fetch data:

const getData = async () => {
  const response = await fetch(process.env.ENDPOINT, options);
  const json = response.json();
  return json;
};

try {
  getData().then((result) => {
    console.log(result);
  });
} catch (error) {
  console.log('There was an error', error);
}

Do I have to use like above try catch or then catch?

Update: Thanks to @bergi's answer:

const getData = async () => {
  const response = await fetch(process.env.ENDPOINT, options);
  const json = response.json();
  return json;
};

    try {
      const result = await getData().then((data) => data);
      res.redirect(`/my-page/?id=${result.data.page.content.id}`);
    } catch (err) {
      console.error(err);
    }

Is this a clean and working approach?

meez
  • 3,783
  • 5
  • 37
  • 91
  • You can use `try` only when you `await` the promise, which you didn't – Bergi Mar 10 '23 at 12:10
  • @Bergi you mean I have to add `await getData()`? But is above a clean solution or is there a better syntax? – meez Mar 10 '23 at 12:17
  • Yes, `try { const result = await getData(); console.log(result); } catch(err) { console.error(err); }` would work. The code you currently have in your question does not work. – Bergi Mar 10 '23 at 12:18
  • @Bergi I added it to my question. Is that like you mean or can it be optimised? – meez Mar 10 '23 at 12:33
  • [Drop the pointless `.then((data) => data)`](https://stackoverflow.com/q/41089122/1048572), otherwise it's fine – Bergi Mar 10 '23 at 12:36

1 Answers1

-1

try { console.log(result); } catch (error) { console.error(error);enter code here }

You can do something like this fetch the response try with successful response and fail with catch if there is some error.

meez
  • 3,783
  • 5
  • 37
  • 91