I often read that async/await
is better than .then()
. I learned, to use await, I need an async function. To handle errors, I need try/catch
. So I built this simple get request:
const isAvailable = async (url) => {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (err) {
console.error(err);
}
};
const fetchedData = isAvailable("/api");
console.log(fetchedData); // Returns: Promise {status: "pending"}
When I see this, it is somehow logical for me, but I can't really understand it.
fetch()
returns a Promise, thus fetchedData
is a Promise. But the try block shout return an object, thus fetchedData
should be a Promise. Even when I see this, it is somehow logical for me, but I can't really understand it, either. fetchedData
is a pending Promise and should be awaited as well, so I tried:
const fetchedData = await isAvailable("/api"); //SyntaxError: Unexpected identifier 'isAvailable'. Expected ';' after variable declaration.
console.log(fetchedData);
I'd say this is because I call await
without being in an async function, so I ended with:
isAvailable("/api").then((fetchedData) => {
console.log(fetchedData);
});
But now I'm back to .then()
what I want to avoid in my exercise.