Eduardo
Eduardo

Reputation: 99

Call async/await functions in parallel not working on React's componentDidMount

I'm trying to call the same this.func twice asynchronously, this.func makes a http request but I can see through the network tab that these two functions are not running in parallel. I've already read these answers: answer 1, answer 2

    async componentDidMount() {     
   //...
    var applicationVersion2 = await Promise.all([this.func(this.state.applicationUrl), this.func(this.state.applicationUrl2)]); 
   //...
    }

how it is now:

enter image description here

how it should be:

enter image description here

Upvotes: 1

Views: 720

Answers (1)

Jay Allen
Jay Allen

Reputation: 485

As I mentioned in the comments above, I suspect that this.func isn't asynchronous code and/or returning a promise although without seeing it, it's hard to say for sure. Try this:

async componentDidMount() {     
  //...
  const first = this.func(this.state.applicationUrl)
  console.log(`First: ${first}`)   
  const second = this.func(this.state.applicationUrl2)
  console.log(`Second: ${second}`) 
  const applicationVersion2 = [await first, await second]
  //...
}

In your console.log, you should see:

First: Promise {<pending>}
Second: Promise {<pending>}

But I'm guessing you'll see a non-promise value from both. If that's the case, make this.func an async function or return a Promise from it.

Upvotes: 1

Related Questions