2 回答
TA贡献1770条经验 获得超3个赞
利用apipromises原生返回fetch,多个请求可以一个接一个的链接
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)
})
TA贡献1834条经验 获得超8个赞
尽管答案已被接受,但请尝试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 ...
})();
添加回答
举报
