我正在尝试使用promise.all从restcountries.eu API中访问数据,但我无法弄清楚自己在做什么。
function displayCurrency(currencyone, currencytwo) {
Promise.all([
fetch(`https://restcountries.eu/rest/v2/currency/${currencyone}`),
fetch(`https://restcountries.eu/rest/v2/currency/${currencytwo}`)
])
.then(function (responses) {
return responses.map(function (response) {
return response.json();
});
}).then(function (data) {
console.log(data[0]);
}).catch(function (error) {
console.log(error);
});
}
data [0]显示带有数组的已解决的Promise。我尝试访问数组中的数据,例如“名称”和“货币”,但我一直都处于未定义状态。
答案 0 :(得分:0)
映射后,您将创建一个.json()
调用数组-一个Promises数组。您需要再次致电Promise.all
。
// Not actually runnable, just hidden by default;
// this is very inelegant, use the other method instead
function displayCurrency(currencyone, currencytwo) {
const arrOfJsonProms = Promise.all([
fetch(`https://restcountries.eu/rest/v2/currency/${currencyone}`),
fetch(`https://restcountries.eu/rest/v2/currency/${currencytwo}`)
])
.then(function (responses) {
return responses.map(function (response) {
return response.json();
})
});
Promise.all(arrOfJsonProms)
.then(function (data) {
console.log(data[0]);
}).catch(function (error) {
console.log(error);
});
}
但是在初始.json
内调用Promise.all
会更优雅,这样代码更简单 ,您不必等待每个连接在下载正文之前进行初始化:
function displayCurrency(currencyone, currencytwo) {
Promise.all([
fetch(`https://restcountries.eu/rest/v2/currency/${currencyone}`).then(res => res.json()),
fetch(`https://restcountries.eu/rest/v2/currency/${currencytwo}`).then(res => res.json())
])
.then(function (data) {
console.log(data[0]);
}).catch(function (error) {
console.log(error);
});
}
答案 1 :(得分:0)
您也可以使用async/await
,如下所示:
const displayCurrency = async (currencyone, currencytwo) => {
try {
let responses = await Promise.all([
fetch(`https://restcountries.eu/rest/v2/currency/${currencyone}`),
fetch(`https://restcountries.eu/rest/v2/currency/${currencytwo}`),
]);
let data = await Promise.all(
responses.map(async (response) => await response.json())
);
console.log(data[0]);
} catch (error) {
console.log(error);
}
};
displayCurrency("eur", "aud");