使用Fetch API时,为何.then(response => console.log(response.originator.name))无输出?
问题原因及解决办法
你的问题出在Promise链式调用的返回值处理上:
- 第二个
.then回调里只执行了console.log(response.content),没有返回任何值,JavaScript函数默认返回undefined - 因此第三个
.then接收的参数response是undefined,自然无法访问originator.name属性
修正方案一:在第二个.then中返回响应数据
function getQuote(){ fetch('https://quotes15.p.rapidapi.com/quotes/random/', options) .then(response => response.json()) .then(response => { console.log(response.content); return response; // 返回response,让后续then能拿到完整数据 }) .then(response => console.log(response.originator.name)) .catch(err => console.error(err)); }
修正方案二:将两个打印操作放在同一个.then中
这种方式更简洁,避免链式传递的冗余:
function getQuote(){ fetch('https://quotes15.p.rapidapi.com/quotes/random/', options) .then(response => response.json()) .then(response => { console.log(response.content); console.log(response.originator.name); }) .catch(err => console.error(err)); }
核心逻辑:Promise的.then会把当前回调的返回值作为下一个.then的参数,如果你需要在后续链式调用中继续使用之前的响应数据,必须在当前回调中显式返回它。
内容的提问来源于stack exchange,提问作者HLee
相关产品推荐
相关产品推荐

