Why is .then() not returning the values expected from JavaScript fetch?

Viewed 35

So the question is pretty straightforward. Why does this work:

fetch("https://api.github.com/users/vampaynani/repos")
  .then((res) => res.json())
  .then((repos) => {
    console.log(repos);
    this.setState({ repos });
  });

But this does not:

fetch("https://api.github.com/users/vampaynani/repos").then((repos) => {
      var r = repos.json();
      this.setState({ repos: r });
    });

Here is the sandbox link for it: SandBox

Maybe my understanding is wrong, but in my eyes these look to be doing the same thing.

2 Answers

This is because repos.json() is a promise that needs to be resolved (awaited) before.

fetch("https://api.github.com/users/vampaynani/repos").then(async (repos) => {
      var r = await repos.json();
      this.setState({ repos: r });
});

Since repos.json() returns a Promise. It's an async function.

Related