Javascript js新闻api承诺无法获取某些值
我有一个js函数,可以获取头条新闻。它以承诺的形式返回,但我无法访问这些文章。这是我的密码Javascript js新闻api承诺无法获取某些值,javascript,Javascript,我有一个js函数,可以获取头条新闻。它以承诺的形式返回,但我无法访问这些文章。这是我的密码 函数news09(){ var url='1〕https://newsapi.org/v2/top-headlines?' + “国家=美国&”+ ‘apiKey=KEY’; var req=新请求(url); 控制台日志(req) 获取(请求) .then(resp=>resp.json()) .then(({articles})=>console.log(articles)) .then(conso
函数news09(){
var url='1〕https://newsapi.org/v2/top-headlines?' +
“国家=美国&”+
‘apiKey=KEY’;
var req=新请求(url);
控制台日志(req)
获取(请求)
.then(resp=>resp.json())
.then(({articles})=>console.log(articles))
.then(console.log([“0”].author));
我看到两个问题
首先,您必须为promise提供一个函数,然后为promise方法提供一个函数
.then(console.log(["0"].author));
.then(({articles}) => console.log(articles))
将立即执行console.log
,并且由于您正在记录数组的属性author
(该属性没有此类属性),因此您将始终获得未定义的
第二,线路:
.then(console.log(["0"].author));
.then(({articles}) => console.log(articles))
将记录从获取中获取的对象的articles属性,但返回undefined,因为您不转发articles
值,所以只记录它。因此,任何。然后该点之后的函数将接收undefined
作为其参数
您可以这样修改代码以修复这些问题:
function news09() {
var url = 'https://newsapi.org/v2/top-headlines?' +
'country=us&' +
'apiKey=13f8c711183c43c1b74dd5912de8310a';
var req = new Request(url);
console.log(req)
fetch(req)
.then(resp => resp.json())
// Make sure to return articles from this function after logging it
.then(({articles}) => { console.log(articles); return articles; })
// Take the articles as an argument, then log the author property of the first entry.
.then(articles => console.log(articles["0"].author));
我看到两个问题
首先,您必须为promise提供一个函数,然后为promise方法提供一个函数
.then(console.log(["0"].author));
.then(({articles}) => console.log(articles))
将立即执行console.log
,并且由于您正在记录数组的属性author
(该属性没有此类属性),因此您将始终获得未定义的
第二,线路:
.then(console.log(["0"].author));
.then(({articles}) => console.log(articles))
将记录从获取中获取的对象的articles属性,但返回undefined,因为您不转发articles
值,所以只记录它。因此,任何。然后该点之后的函数将接收undefined
作为其参数
您可以这样修改代码以修复这些问题:
function news09() {
var url = 'https://newsapi.org/v2/top-headlines?' +
'country=us&' +
'apiKey=13f8c711183c43c1b74dd5912de8310a';
var req = new Request(url);
console.log(req)
fetch(req)
.then(resp => resp.json())
// Make sure to return articles from this function after logging it
.then(({articles}) => { console.log(articles); return articles; })
// Take the articles as an argument, then log the author property of the first entry.
.then(articles => console.log(articles["0"].author));
你到底希望该语句做什么?数组没有author
属性,这是你希望知道的。此外,你调用的是函数,而不是将函数引用传递给。然后()
,这将导致它立即执行,这可能是您不希望的。您到底希望该语句做什么?您希望知道,数组没有author
属性。此外,您正在调用函数,而不是将函数引用传递给。然后()
,这将导致它立即执行,这可能是您无意的。