我正在尝试从NewsAPI中提取数据-我所获得的API的结果是一个可解决的承诺,我不知道如何访问其中的对象。
///////////////////SAMPLE CODE
let raps;
var url = 'https://newsapi.org/v2/top-headlines?' +
'category=sports&' +
'q=raptors&' +
'apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxx';
var req = new Request(url);
fetch(req)
.then(function(response) {
raps = response.json();
return raps;
});
function data () {
if(raps == undefined) {
console.log("Data is being parsed")
} else {
console.log(raps);
clearInterval(loadData);
generateData(raps);
}
}
const loadData = setInterval(data, 1000);
function generateData(raps) {
let newData = raps.articles;
console.log(newData);
}
/////////////////END OF SAMPLE CODE
What I'm getting back is:
Promise {<resolved>: {…}}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
articles: (20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
status: "ok"
totalResults: 26
我正在尝试访问articles数组。
答案 0 :(得分:0)
这应该有效...
let raps;
var url = 'https://newsapi.org/v2/top-headlines?' +
'category=sports&' +
'q=raptors&' +
'apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxx';
var req = new Request(url);
fetch(req)
.then(response => response.json())
.then((data) => {
raps = data;
});
function data () {
if(raps == undefined) {
console.log("Data is being parsed")
} else {
console.log(raps);
clearInterval(loadData);
generateData(raps);
}
}
const loadData = setInterval(data, 1000);
function generateData(raps) {
let newData = raps.articles;
console.log(newData);
}
答案 1 :(得分:0)
以下内容可一次检索文章。您的想法似乎是每秒轮询服务器,但可以轻松地对其进行调整。我使用了更新的async/await
方法,将异步查询视为同步查询,使我更容易阅读和理解,但是如果您仍然可以使用fetch/then/catch
再次,应该不难重构。
进一步解释我的代码。
(async () => { ...})();
块中。await
基本上是指等到resolved
。这样您就可以看到我等待提取解决,然后等待响应json解决(这实际上是您的解决方案中缺少的一点)fetch('https://api.com/values/1')
.then(response => response.json())
.then(json => console.log(json));
///////////////////SAMPLE CODE
(async () => {
const url = 'https://newsapi.org/v2/top-headlines?' +
'category=sports&' +
'q=raptors&' +
'apiKey=xxxxxxxxxxxxxxxxxxxxxx';
const response = await fetch(url);
let articles = null;
if (response.ok) {
const raps = await response.json();
articles = raps.articles;
}
if (articles) {
articles.forEach(article => console.log(article));
} else {
console.log('No articles');
}
})();
/////////////////END OF SAMPLE CODE