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 badges2 Answers
Reset to default 3Making 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 ...
})();
本文标签:
版权声明:本文标题:node.js - Need to call multiple api in serial order, one after the other in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744081331a2587697.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论