// 定义一个函数,用于调用第一个接口并获取数据
function callFirstAPI() {
return fetch('/firstAPI')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
console.error('Error fetching firstAPI:', error);
throw error; // 抛出错误,使得后续处理可以捕获到错误
});
}
// 定义一个函数,用于调用第二个接口并传入第一个接口返回的数据作为参数
function callSecondAPI(dataFromFirstAPI) {
return fetch('/secondAPI', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ parameter: dataFromFirstAPI })
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
console.error('Error fetching secondAPI:', error);
throw error; // 抛出错误,使得后续处理可以捕获到错误
});
}
// 调用第一个接口,然后在获取到数据后调用第二个接口,并处理第二个接口返回的数据
callFirstAPI()
.then(dataFromFirstAPI => {
// 使用第一个接口返回的数据调用第二个接口,并处理第二个接口返回的数据
return callSecondAPI(dataFromFirstAPI);
})
.then(dataFromSecondAPI => {
// 处理第二个接口返回的数据
console.log('Data from secondAPI:', dataFromSecondAPI);
})
.catch(error => {
// 处理错误
console.error('Error:', error);
});