我目前正在嘗試從公共 API 中獲取有關一個國家及其鄰國的資料,以在我的 html 上呈現。
renderCountry() 是一個函式,用于在我的 html 上實作我將收到的資料。
我還排除了一些不必要的代碼,我認為這在這種特殊情況下并不重要。
這就是我獲取資料的方式:
const getCountryAndNeighbour = function(country) {
fetch(`https://restcountries.com/v2/name/${country}`)
.then(response => response.json())
.then(data => {
renderCountry(data[0]);
const neighbour = data[0].borders;
neighbour.forEach(country => {
fetch(`https://restcountries.com/v2/alpha/${country}`)
.then(response => response.json())
.then(data => renderCountry(data, `neighbour`))
});
})
}
在這里,您將看到回呼地獄架構。有什么逃避的想法嗎?提前致謝。
uj5u.com熱心網友回復:
您可以嘗試使用async / await。您可以async在 function 關鍵字之前添加并根據需要添加 await。請參閱下文以了解此操作:
const getCountryAndNeighbour = async function (country) {
const res = await fetch(`https://restcountries.com/v2/name/${country}`)
const data = await res.json();
renderCountry(data[0]);
const neighbour = data[0].borders;
await Promise.all(
neighbour.map(async country => {
let response = await fetch(`https://restcountries.com/v2/alpha/${country}`)
response = await response.json();
return renderCountry(response, 'neighbour');
});
);
}
uj5u.com熱心網友回復:
您可以使用async/await重寫它
例如。
const getCountryAndNeighbour = async country => {
const response = await fetch(`https://restcountries.com/v2/name/${country}`);
const data = await response.json();
renderCountry(data[0]);
const neighbour = data[0].borders;
neighbour.forEach(async country => {
const response = await fetch(`https://restcountries.com/v2/alpha/${country}`)
const data = await response.json();
renderCountry(data, `neighbour`);
});
};
請注意,forEach 將同時運行所有的 Promise。
如果你想一個一個地運行,你應該使用例如。for 回圈或諸如Bluebird.map之類的一些實用程式,它允許您指定并發性
祝你好運!
uj5u.com熱心網友回復:
這將使用 Async/await
async function getCountryData(country) {
const response = await fetch(`https://restcountries.com/v2/name/${country}`);
return await response.json();
}
async function getNeighbourData(country) {
const response = await fetch(`https://restcountries.com/v2/alpha/${country}`);
return await response.json();
}
async function getCountryAndNeighbour(country) {
const data = await getCountryData(country);
const neighbourCountries = data[1].borders;
for (const neighbour of neighbourCountries) {
const response = await getNeighbourData(neighbour);
console.log(response);
}
}
在您的函式中檢查 [0]/[1] 時添加必要的驗證。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/417772.html
標籤:
上一篇:批量Python異步API請求
