gpt4 book ai didi

javascript - 如何从已解析的 Promise javascript 中提取数据?

转载 作者:行者123 更新时间:2023-12-02 23:40:03 25 4
gpt4 key购买 nike

我正在尝试从 NewsAPI 中提取数据 - 我得到的 API 的结果是一个已解决的 promise ,但我不知道如何访问其中的对象。

///////////////////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

我正在尝试访问文章数组。

最佳答案

这应该有效...

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);
}

关于javascript - 如何从已解析的 Promise javascript 中提取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56120414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com