2 回答

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
利用apipromises原生返回fetch,多個(gè)請(qǐng)求可以一個(gè)接一個(gè)的鏈接
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貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
盡管答案已被接受,但請(qǐng)嘗試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 ...
})();
添加回答
舉報(bào)