Why is it necessary to use 'then' on the response JSON when using the Fetch API? It's like trying to decipher the hidden meaning

While delving into the realm of promises, I decided to test it out with a basic GET request on Twitch. Yet, one aspect is still puzzling me - why does json() return a promise? The response already contains the data, so what's the deal with it being wrapped in another promise?

fetch('https://api.twitch.tv/kraken/games/top?limit=10&offset=0')
    .then( resp => {
        resp.json()
            .then(function(data) {  
                        console.log(data);  
        });
  });

To put it differently: I grasp that the first then statement waits for the response. However, once inside the function of that then block, shouldn't the data be readily accessible without an additional promise since the response has already been received? This whole situation just leaves me scratching my head.

Answer №1

According to information found in the source:

When a fetch() request is made, the response received is in the form of a Stream object. This indicates that when we utilize the json() method, a Promise will be generated due to the fact that the stream's reading process occurs asynchronously.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS view fails to reflect updates in the model

This issue with Angular has been widely discussed online, but I ask for your patience. I have tried various solutions without success. Here is a simplified version of my code: View: <div ng-hide="{{beHidden}}"></div> Controller: // Set beHi ...

Having difficulty parsing JSON data using the MiniJson-Reader library

Recently, I encountered an issue while attempting to parse a JSON string in my C++ code using the library minijson. The snippet of code causing trouble is as follows: <<"version">> [&]() { result.setVersion(v.as_long()); } ...

Emphasize the most recent file during the document upload process and ensure the scroll bar moves accordingly to the document

I am currently working on a feature where the scroll bar should move to the newly uploaded document in a list of documents. When I upload a new document, I want the scroll bar to automatically move to that document. Currently, the highlighting changes to t ...

Tips for sending an array of "FormData" through ajax and retrieving it in a Laravel controller

# Could you please provide guidance on sending this array to the controller via Ajax request? var dataPanier=[]; function addarray(objser) { dataPanier.push(objser); } $('.target').click(function() { var btn_name=$(this).attr("name"); ...

Reading JSON messages in a request on the server side of a RESTful service: A comprehensive guide

I am having trouble reading JSON data that is being sent from a client to a service. Despite trying multiple methods, the console continues to display an empty object. //Service: My service @Path("signup") public class signupservice { @P ...

Display a container using Fancybox

With just a click of a button, I want to reveal a hidden div in an elegant box. Here's the code snippet that actually works: $("#btnForm").fancybox({ content: $("#divForm").html() }); However, after doing some research, it appears that this may not ...

Next.js encountered an API resolution issue while uploading a file, resulting in no response being

Even though my code is functioning properly, a warning appears in the console: The API call was resolved without sending any response for /api/image-upload This particular endpoint is responsible for uploading an image to Digital Ocean's object sto ...

Retrieving data from JSON arrays based on specific conditions in Java

I have been utilizing Unirest to retrieve all IDs from an endpoint. The array structure is as follows: [ { "date": "2022-04-05", "timeIn": "2022-04-05 07:00:00", "timeOut": " ...

Encountered an unexpected forward slash while trying to parse JSON using

When passing a file, why does the `parseJSON` function fail? The file is stored in variable a and then I attempt to parse it using `parseJSON`. var a = "/android/contents/img/uploads/img_2A0.png"; var result = jQuery.parseJSON(a); The error being displa ...

Ensure the page is always updated by automatically refreshing it with JavaScript each time it

I'm currently working on a web application that makes use of JQuery. Within my javascript code, there's a function triggered by an onclick event in the HTML which executes this line: $('#secondPage').load('pages/calendar.html&apos ...

Can you explain the distinction between incorporating and excluding the keyword "await" in the following code snippets?

Currently, I'm diving into an MDN article that covers async/await. I've grasped the rationale behind using the async keyword preceding functions, yet there's a bit of uncertainty regarding the await keyword. Although I've researched "aw ...

"Trouble with server communication: data array not being passed to hbs

In my GET route, I have the following: app.get(("/employee/:id"), (req, res) => { data.getEmployeeByNum(req.params.id).then((data) => { res.render("employee", {employee: data}); }).catch(function(reason) { res.render("employe ...

top-notch cloud option for handling JSON requests

I am currently developing an Android app that needs to access JSON data from three different websites at specific intervals throughout the day. In order to simplify this process, I am seeking a cloud solution that enables me to utilize scripting languages ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...

JavaScript and HTML are commonly used programming languages for developing

By utilizing JavaScript, I was able to generate a table dynamically based on user input. For example, if the user enters 3 and clicks "go", a table with 3 rows is created. Using the .keyup function allowed me to target a column successfully. However, an i ...

Utilizing the EJS access to retrieve express variables within a JavaScript onload function

When working with variables in an EJS file, you can easily access their values. For example: <h1><%= title %></h1> Now, if you want to use the same 'title' variable in an onload JavaScript function on the same EJS page, how wo ...

Ensure that the sidebar automatically scrolls to the bottom once the main content has reached the bottom

I am facing an issue with a sticky sidebar that has a fixed height of calc(100vh-90px) and the main content. The sidebar contains dynamic content, which may exceed its defined height, resulting in a scrollbar. On the other hand, the main content is lengthy ...

Tips on how child component can detect when the object passed from parent component has been updated in Angular

In the child component, I am receiving an object from the parent component that looks like this: { attribute: 'aaaa', attribute2: [ { value }, { value }, { value }, ] } This object is passed to th ...

Including variables in package.jsonORInjecting variables into package

I'm currently developing a React application and I am trying to figure out how to pass a variable from the .env file into package.json: {"proxy": "ENV_VAR"} Is there a way to achieve this? In addition, our app is built using Docker. Is it possible ...

What is the reason for DialogContent displaying a scroll bar instead of expanding further when nested Grids with spacing are included?

My current project involves working on a form displayed in a dialog window. To adjust the layout of the form's fields, I utilize multiple Grid elements nested within another Grid. However, I've encountered an issue where adding any spacing to the ...