0

I'm using axios to fetch some data form my API, after the first promise is resolved, I execute another one after that.

I tried something that did work, but it does not seems correct, the problem is that for the firstResolvedPromise() I don't need the return data from it, I just need the JavaScript to wait it's resolution to then execute the other promise, knowing this, the data => { } is useless code, how can I do it better? Omit the data?

firstResolvedPromise()
  .then(data => {
    secondResolvedPromisse()
      .then(data => {
        this.setState({
          someState: data,
        })
      })
  })
Pedro Vieira
  • 2,266
  • 1
  • 20
  • 35
  • Possible duplicate of [How to wait for a JavaScript Promise to resolve before resuming function?](https://stackoverflow.com/questions/28921127/how-to-wait-for-a-javascript-promise-to-resolve-before-resuming-function) – str May 22 '19 at 18:22
  • My question is not about how to synchronize axios calls, I've already managed that, the question is about how to omit the data parameter since Im not using it. – Pedro Vieira May 22 '19 at 18:31
  • 1
    Sure, just omit the `data` parameter and use only `()`. But there is no harm in spelling it out either. Btw, if you don't need any data from the call, why have them run in sequence at all? – Bergi May 22 '19 at 18:33
  • Because this function fetches a list and cache it somewhere, the other promise or other components consume those list items – Pedro Vieira May 22 '19 at 18:50
  • 1
    @PedroVieira , that doesn't sound like good program design. The state of an external cache is indeterminate, even if we're talking mere milliseconds later. You should aim to deliver the data directly to the `.then()` callback, and pass it on as required to other functions/API calls. – Roamer-1888 May 22 '19 at 20:00

1 Answers1

2

You should chain the promises:

firstResolvedPromise()
  .then(() => secondResolvedPromisse())
  .then(data => this.setState({
      someState: data,
   }))
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964