【发布时间】:2018-04-05 21:53:32
【问题描述】:
所以我有一个表格,其中填充了来自 API 的数据。现在我想添加一个<p> 标记,其中包含数据中的平均质量键。这是我必须获得效果很好的表数据的代码:
const url = 'https://swapi.co/api/species/1/';
function fetchData(url) {
return fetch(url).then((resp) => resp.json());
}
function constructTableRow(data) {
const row = document.createElement('tr');
const { name, height, mass, hair_color } = data;
row.appendChild(constructElement('td', name))
row.appendChild(constructElement('td', height))
row.appendChild(constructElement('td', mass))
row.appendChild(constructElement('td', hair_color))
return row;
}
const swTable = document.getElementById('sw-table').getElementsByTagName('tbody')[0];
fetchData(url).then(data =>
data.people.forEach(personUrl =>
fetchData(personUrl).then(result => {
const row = constructTableRow(result);
swTable.appendChild(row);
})
)
);
现在这是我必须得到平均值的代码,但它不起作用:
const link = 'https://swapi.co/api/species/1/';
function fetchLink(link) {
return fetch(link).then((resp) => resp.json());
}
fetchLink(link).then(data =>
data.people.forEach(personUrl =>
fetchData(personUrl).then(result => {
const getMass = result.mass;
return getMass.reduce(function(a, b) {
return a + b;
}) / getMass.length;
})
)
);
当我运行这段代码时,我得到了这个错误:
Uncaught (in promise) TypeError: getMass.reduce is not a function at fetchData.then.result
我可以以某种方式改变它以在这个 fetch 内部运行还是我必须有一个单独的函数?
【问题讨论】:
-
getnMass拼写错误 -
@nirus 谢谢,但它仍然给出同样的错误。
-
你确定响应数据是 json,如果我只是在浏览器中输入 url,我会得到一个 HTML 页面,而不仅仅是 .json
-
fetchData函数长什么样?此外,您的数据源中的某些人拥有mass: "unknown",您可能希望将其过滤掉。 -
@SebastianSpeitel 它从 swapi.co/api/people/1/?format=json 解析
标签: javascript function fetch es6-promise