您遇到的问题是由于在您的标准JavaScript函数中,您没有返回
MyResults.json()
的结果。
fetch
api依赖于每个API的返回值
.then()
将其传递到下一个
.then()
.then()
将接收
undefined
。
在这里您可以修复代码:
箭头功能版本(工作)
fetch('https://reqres.in/api/users')
.then(MyResults => MyResults.json())
.then(MyData => console.log(MyData));
标准JavaScript函数(固定)
fetch('https://reqres.in/api/users')
.then(
function MyFunction1(MyResults) {
return MyResults.json(); // Add `return` here
}
)
.then(
function MyFunction2(MyData) {
console.log(MyData); // Now `MyData` will contain the JSON data
}
);
解释
arrow函数版本
:
MyResults => MyResults.json()
隐式返回MyResults.json()
.then()
。
:在
MyFunction1
return
MyResults.json()
return
,MyFunction1
返回
undefined
MyFunction2
接收
undefined
而不是json data。
return
很重要方法期望回调函数将返回将传递给下一个
.then()
的值(或承诺)。
如果您不返回任何东西,那么下一个会收到
.then()
。afling full示例带有错误处理
.then()
undefined
确保正确处理响应的任何网络错误或问题。