【发布时间】:2020-03-29 09:21:17
【问题描述】:
所以情况就是这样:我正在尝试从 Promise 中获取特定数据。 Promise 显示来自 API 的数据:https://api.covid19api.com/country/netherlands/status/confirmed
Promise 由三个值(0、1 和 2)组成,每个值由一个包含多个变量的数组组成。我想从 Promise 名称 '0' 的数组中的最后一个变量中获取数据(你明白吗?)。
这是 Promise 的样子: Here you can see it consists of the values 0, 1 and 2
点击后:I try to get the data from the array (PromiseValue I believe it is called?)
这就是我想要的数据:数组中最后一个变量的数据。从这个变量中,我想要来自“案例”的数据,所以是“8603”。 This is the data I try to get
function getAPIdata() {
var url = 'https://api.covid19api.com/country';
var country = document.getElementById('country').value;
var requestConfirmed = url + '/' + country + '/' + 'status' + '/' + 'confirmed';
var requestRecovered = url + '/' + country + '/' + 'status' + '/' + 'recovered';
var requestDeaths = url + '/' + country + '/' + 'status' + '/' + 'deaths';
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
Promise.all([
fetch(requestConfirmed, requestOptions),
fetch(requestRecovered, requestOptions),
fetch(requestDeaths, requestOptions)
])
.then(function (responses) {
return responses.map(function (response){
if(!response.ok) throw Error(response.statusText);
return response.json();
});
}) .then(function(result){
onAPISucces(result);
// console.log(result);
}) .catch(function (error){
onAPIError(error);
});
}
function onAPISucces(result) {
var type = result;
var landenLijst = result;
console.log(landenLijst);
var country = document.getElementById('country').value;
// console.log(landenLijst[landenLijst.length - 1].Cases);
for(var i=0; i < landenLijst.length; i++);
// console.log(landenLijst[i].TotalConfirmed);
var totaalAantalBesmettingen = landenLijst[0].PromiseValue[PromiseValue.length - 1];
var totaleBesmettingen = document.getElementById('confirmedInformation');
totaleBesmettingen.innerHTML = totaalAantalBesmettingen;
}
function onAPIError(error) {
console.error('Oeps, foutje!', error);
var totaleBesmettingen = document.getElementById('confirmedInformation');
totaleBesmettingen.innerHTML = 'Please try again. Did you enter a country?';
}
document.getElementById('zoek').onclick = function(){
getAPIdata();
};
<body>
<form>
<fieldset>
<legend>Choose a country:</legend>
<label for="country">Country:</label>
<input type="text" name="country" id="country" placeholder="For example: Belgium"/>
<input type="button" id="zoek" value="Search" />
</fieldset>
</form>
<p id="confirmedInformation"></p>
<p id="recoveredInformation"></p>
<p id="deathsInformation"></p>
<p id="test"></p>
</body>
我被困在下面的代码中(您可以在我的 JavaScript 代码中找到)。我不知道如何从数组中获取特定数据。你知道我做错了什么吗?
var totaalAantalBesmettingen = landenLijst[0].PromiseValue[PromiseValue.length - 1];
【问题讨论】:
标签: javascript api promise