這是我用于專案的代碼,它適用于國家 1,但不適用于國家 2。國家 2 給出未定義的錯誤
const getCountryData = function (country) {
//country 1
fetch(`https://restcountries.com/v3.1/name/${country}`)
.then(response => response.json())
.then(data => {
renderCountry(data[0]);
const neighbour = data[0].borders[0];
console.log(data[0]);
//if theres no neighbour return immedaitely
//thats what the ! is for
if (!neighbour) return;
//country 2
return fetch(`https://restcountries.com/v3.1/alpha/${neighbour}`);
})
.then(response => response.json())
.then(data => renderCountry(data, 'neighbour'));
};
getCountryData('nigeria');
這是錯誤輸出:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'png') at renderCountry (script.js:48:55) at script.js:158:19
uj5u.com熱心網友回復:
請注意您對 renderCountry 的兩次呼叫之間的區別。第一個用第一個資料元素呼叫函式,第二個用整個資料陣列呼叫函式。
嘗試
.then(data => renderCountry(data[0], 'neighbour'));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/508500.html
標籤:javascript 异步 异步等待 打回来