Fetch Confusion
I am learning JS. My question is when i am getting this object from fetch how do i use it outside fetch
suppose i have to display all the names from the data on the webpage. how do i do that?
4 Replies
Inside the second
then
block. When working with Promises, which basically is JavaScript's lingo for "variables that will eventually hold some value", you have to wait for them and only until then you can use them in your app. For example:
Obviously this is as simple as it gets, but the point if that you have to work inside the then
block. Note that other parts of the code will not have access to users (btw I renamed that parameter name to better reflect what is holds, as "data" was too generic).
There's also an alternative syntax called async/await
where you can specify the code to wait until it resolves. It's the same thing, but written differently and in such a way that looks like regular, synchronous code.
Usually you use this syntax within functions, and you have to explicitly label them as async
but I think since Node 18 you can use await
at the top level.
Ahhh, Thank you sooo much
Soo, if I use .then I won't be able to use the data outside and if i use async function and hold it in a variable with await
I'll be able to use it globally
That's correct?
Am getting this error
This worked
but i want to know if this is the right way of getting the data ?
Yes, that's how you do it. There are other things you can consider for more complicated situations where you want to be able to abort a request or continuously repeat it every few seconds, and things like that. But at its core that's how simple it really is.
One thing you should know however is that sometimes you may make a request to a resource that for whatever reason is not available or does not exist. In those cases there will be no error thrown, and your
catch
block will not run. You need to explicitly check if the request was ok:
Here, response.ok
simply checks if the status code is anything other than a 200 (which is standard convention accepted as "everything is ok"). The fact that a request returned a 404 does not meant that the request failed: it did what you asked for, make arequest and give you a response, but it simlpy wasn't the response you were expecting so you must explicitly check for that yourself.That helps, thank you sooo muchh ❤️ @Joao