我需要在JavaScript中按顺序依次调用多个API,其中一个的响应可能需要作为另一个的输入。有人能否提供建议或示例代码。
我尝试使用 .fetch() API,但发现很难将一个API的响应传递给另一个API。
我需要在JavaScript中按顺序依次调用多个API,其中一个的响应可能需要作为另一个的输入。有人能否提供建议或示例代码。
我尝试使用 .fetch() API,但发现很难将一个API的响应传递给另一个API。
fetch
API本身返回的promises
,可以将多个请求连接在一起。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)
})
async
和await
来改进代码。
(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 ...
})();
fetchJson
辅助函数,既可以获取数据,又可以等待结果的.json()转换,将有助于简化代码。 - Wyck