例子:
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((e) => {
console.error(`network error : ${e}`);
});
fetch第一层回调的结果response是什么,为什么返回的数据是在第二层then里面?
response是Response对象,包含Header、status、statusText等属性。要获得具体数据需要使用.json(用于JSON)、.text(用于文本)、.formData(用于FormData对象)等方法。
至于为什么需要return,因为Response.json返回的是一个Promise,所以只能先return,再在下一层处理。
如果想要在第一层就要获取数据该怎么写?
答:
fetch(url)
.then(async e => {
const { code, data } = await e.json()
if (code === 200) {
console.log(data)
}
})
.catch((e) => {
console.error(`network error : ${e}`);
});