Petur Ulev
Petur Ulev

Reputation: 97

Javascript two api calls

Basically I want to call an API twice, make an array [res1, res2] of the two responses, and then operate on this array. My code goes something like that:

function f() {
  apiCall1(params1)
    .then(response1 => [response1, apiCall2(params2)])
    .then(data => someFunction(data))
}

Unfortunately, this method does not work. I get undefined properties of data[0] and data[1]. However, if I make only one API call, everything works fine. I am wondering whether my syntax is wrong and also what would be a good way to implement this? Thanks.

Upvotes: 0

Views: 46

Answers (1)

giuseppedeponte
giuseppedeponte

Reputation: 2391

You can group promises with Promise.all, for example:

function f() {
  Promise.all([apiCall1(params1), apiCall2(params2)])
    .then(data => {
       const response1 = data[0];
       const response2 = data[1];
    })
}

cf. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Upvotes: 2

Related Questions