Understanding fetch/ promises

The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request

why doesnt it just return the response directly, why does it need a promise that resolves to the response, isnt that just an extra step?

Because it is asynchronous. In JS, we generally don’t like blocking code - code that stops the program until that code is done. By returning a Promise, they give you control over how you want to handle that. Maybe you want a timeout? Maybe you want to run a bunch of fetches in parallel and wait for them all to be complete? There are many possibilities.

If you don’t want to deal with the Promise directly, you can try using async/await. It handles the Promise for you and makes the code “look” synchronous.

thanks Kevin that makes sense

JavaScript can only do one thing at one time, so this:

The key thing is when will it return the response? If it returned directly, then nothing else could happen until the response arrived. So if your fetch query happened synchronously, and then takes ten seconds, or a minute, or half an hour, nothing else would work until that response arrives. And by nothing would work, that’s literally nothing on that webpage – no scrolling, clicking etc on a page (this used to be really common).

What you are doing with a Promise is that when you make the request, it wraps it in an JS object with a few specific properties. Then the program carries on. When the request resolves to something (or rejects), one of the properties changes from pending to finished and triggers whatever then does. Callbacks are another way of dealing with this (when this happens, then run that function). And as mentioned there’s async/await, which is a nice, easy to understand syntax that works via promises.

Also, before fetch was introduced, the only method for making in-page HTTP requests (AJAX calls) was XMLHTTPRequest. It [used to] allow exactly what you described (that’s why you got those lockups I said used to be common), but browser vendors deprecated the functionality because it tends to cause very poor user experiences (you can still use it that way, but then you don’t get access to most of the useful stuff it can do).

1 Like

thanks for this explanation, i have a much clearer understanding now of why and what i am writing now when using fetch

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.