MatijaxD
MatijaxD

Reputation: 171

Why does setState in this promise take longer to update than the same code as an async function?

I have 2 versions of the same fetch functions here, the first one uses promises, the second one async-await. To my understanding there should be no difference between those two, so I'd appreciate some clarification to what's actually happening here.

The following version, which uses async-await, sets the state by the time console log runs:

async fetchPostList(query) {
  const response = await fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
  const data = await response.json()
  this.setState({ postList: data });
  console.log(this.state.postList);
}

Console: Array(474) [ ... ]

The version that uses promises sets state after the console log:

fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
    .then( response => response.json())
    .then( data => this.setState({ postList: data }))
  console.log(this.state.postList);
}

Console: Array []

Upvotes: 0

Views: 38

Answers (2)

ufollettu
ufollettu

Reputation: 882

If you want to log the updated state you must wait the Promise to resolve some data, only when you have data you can log the data itself:

fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
   .then( response => response.json())
   .then( data => {
     this.setState({ postList: data })
     // here you have data
     console.log(this.state.postList);
   })
// here you do not have data
}

Upvotes: 2

Mark
Mark

Reputation: 92450

The first function is an async function. In an async function the code pauses while the awaited promises resolve.

async fetchPostList(query) {
  const response = await fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
  /* Pause ...*/

  const data = await response.json() 
  /* Pause ... */

  this.setState({ postList: data });
  console.log(this.state.postList);
}

The second function is not async, which means it runs to completion. It just fires off the promises and callbacks and continues, so the console.log() is called immediately after creating the promises.

fetchPostList(query) {
  fetch(`https://hacker-news.firebaseio.com/v0/${query}.json`)
    .then( response => response.json())
    .then( data => this.setState({ postList: data }))

  /* does NOT pause */
  console.log(this.state.postList);
}

Upvotes: 3

Related Questions