Need to call multiple api in serial order, one after the other in javascript

Viewed 5230

I need to call multiple api in serial order one after the other in javascript. The response of one might need to act as input to other. Can someone please suggest or give a sample code.

I tried to use the .fetch() api, but finding it difficult to pass the response of one api to other.

2 Answers

Making use of promises which are returned natively by the fetch api, multiple requests can be chained one after another

var result = fetch('api/url1') // First request
    .then(function (response) {
        return response.json();
    })
    .then(function (data) {
        var secondId = data.someId
        return fetch('api/url2' + secondId); // Second request
    })
    .then(function (response) {
        return response.json();
    })
    .then(function (data) {
        var thirdId = data.someId
        return fetch('api/url3' + thirdId); // Third request
    })
    .then(function (response) {
        return response.json();
    })
    .then(function (data) {
        // Response of third API
    })
    .catch(function (error) {
        console.log('Error', error)
    })

Although the answer has been accepted, try async await like so.

(async () => {
  // first
  const res = await fetch("https://reqres.in/api/users/1");
  const result1 = await res.json();
  
  console.log("Result 1", result1);
  
  // some logic ...
  
  // second 
  const res2 = await fetch("https://reqres.in/api/users/2");
  const result2 = await res2.json();
  
  console.log("Result 2", result2);
  // ... so on ...
})();

Related