-1

I'm trying to fetch data from two different APIs and want this to happen in parallell but then I want to wait for them to execute and then continue with the next line of code.

componentDidMount() {
    this._isMounted = true;
    this.fetch1() // <-- Async method
    this.fetch2() // <-- Async method
    this.func(); // The above two lines of code needs to be done to execute this line

  }

  async fetch1() {
    fetch("/api/abc123")
      .then(res => res.json())
      .then(res => {
          this.setState({ foo: res });
      });
  }

  async fetch2() {
    fetch("/api/def456")
      .then(res => res.json())
      .then(res => {
          this.setState({ bar: res });
      });
  }

func() {
    // Do something with the data from the APIs
  }
quieri
  • 345
  • 3
  • 19
  • 1
    Also possible duplicate of https://stackoverflow.com/q/31424561/1260204 – Igor Jul 03 '19 at 18:57
  • Maybe use async on componentDidMount and then use await on your fetches. const fetchOne = await fetch1(); – Modig Jul 03 '19 at 19:00
  • Also a possibility [Call async/await functions in parallel](https://stackoverflow.com/questions/35612428/call-async-await-functions-in-parallel/35612484) – VLAZ Jul 03 '19 at 19:01

2 Answers2

2
const promises = []
for(let request of requests){ promises.push(request) }

Promise.all(promises).then(res => /*res[0], res[1]*/) 

Promise.all will only resolve when all requests are done, and deliver then in an response array in the order passed.

jensgram
  • 31,109
  • 6
  • 81
  • 98
Dupocas
  • 20,285
  • 6
  • 38
  • 56
1

I use axios, it has axios.all() for multiple requess, have a look at these examples

Performing multiple concurrent requests (code from the link)

function getUserAccount() {   
     return axios.get('/user/12345'); 
}

function getUserPermissions() {   
    return axios.get('/user/12345/permissions'); 
}

axios.all([getUserAccount(), getUserPermissions()])  
.then(axios.spread(function (acct, perms) {
    // Both requests are now complete   
}));
its4zahoor
  • 1,709
  • 1
  • 16
  • 23