admin管理员组

文章数量:1359261

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.

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.

Share Improve this question asked Jul 13, 2020 at 4:04 HariHari 671 gold badge2 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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 ...
})();

本文标签: