Hejhejhej123
Hejhejhej123

Reputation: 1195

how to return two results from promise

I am using fetch to get data from two different api:s. I need to use both of the api data in the same function. One is finished much faster than the other, so to make this work I have used promise.all. But now I am stuck with two questions.

  1. How can I return 2 results (test1 and test2) to the next promise? Right now my code stops and says that "test1 is not defined".

  2. If I use promise.all and then run .json on each file (like the code below), will the code wait for each json to finish before returning the result? Or may one not finish?

code:

Promise.all([fetch1, fetch2])
    .then((file) => {
      let test1 = file[0].json()
      let test2 = file[1].json()
      return ([test1, test2])
    }).then((data) => {
      console.log(test1)
      console.log(test2)
    })

Upvotes: 1

Views: 98

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370769

You can return a Promise.all on both .json calls inside the .then:

Promise.all([fetch1, fetch2])
    .then((file) => {
      let test1 = file[0].json()
      let test2 = file[1].json()
      return Promise.all([test1, test2])
    }).then(([test1, test2]) => {
      console.log(test1)
      console.log(test2)
    })

But it would probably be better to take both fetch requests and .map them to their .json() Promises, then call Promise.all on the result:

const getApi = url => fetch(url).then(res => res.json());
Promise.all([
  getApi('url1'),
  getApi('url2')
])
  .then(([test1, test2]) => {
    // do stuff with test1 and test2
  })
  .catch((err) => {
    // handle errors
  });

The above code will result in the requests being processed in parallel; neither request will prevent the other request from continuing. In contrast, your (tweaked) original code will require the response headers from both requests to be received and processed before the .json() (to process the body) for either can start.

Upvotes: 2

Related Questions