fetch 會使用 ES6 的 Promise 作回應
then 作為下一步
catch 作為錯誤回應 (404, 500…)
fetch('https://randomuser.me/api/', {})
.then((response) => {
// 這裡會得到一個 ReadableStream 的物件
console.log(response);
// 可以透過 blob(), json(), text() 轉成可用的資訊
return response.json();
}).then((jsonData) => {
console.log(jsonData);
}).catch((err) => {
console.log('錯誤:', err);
});
ReadableStream
- 回傳的為
ReadableStream
物件,需要使用不同資料類型使用對應方法,才能正確取得資料物件。 - fetch 後方會接 then(),這是 Promise 的特性,資料取得後可在 then 裡面接收。
- Fetch API 的 Response 物件中的 body 屬性提供了一個 ReadableStream 的實體,這個階段我們無法直接讀取資料內容,而 ReadableStream 物件中可用以下對應的方法來取得資料 (https://developer.mozilla.org/zh-TW/docs/Web/API/Body):
資料格式
- arrayBuffer()
- blob()
- formData()
- json()
- text()