例子:
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}`);
});