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?