[JS30] Day06: AJAX Type Ahead
keywords: replace, match, fetch, filter, 資料過濾, 資料篩選
利用 Fetch API 來取得資料
使用 fetch 的時候它會先回傳 Promise 給我們,第一個回傳的是一個 readableStream,我們需要先把它解析成 json 來讀取,在 then 中 return 的內容會到下一個 then 的 callback 中可以使用:
更多關於 Fetch API @ MDN 更多關於 Promise @ PJCHENder Evernote
let cities = [];
const endpoint =
'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
// Step1: Fetch Data
fetch(endpoint)
.then((blob) => blob.json()) // 取得 readableStream,並轉成 json 後 return
.then((data) => {
cities = data; // 把 data 代進去 cities 陣列中
});
console.log(cities); // 這裡會取得不到資料
要注意的是,在上面的程式碼最後,當我們使用 console.log 想要直接看 cities 的內容是,會看到空陣列(未被給 data 的值),這是因為 fetch 裡面的是一個非同步事件,因此console.log其實在 cities 尚未被賦值(cities = data)就執行了。
因此,如果你想要先看到 cities 的值的話,記得要寫在 .then 的這個 callback 當中,像是這樣:
更多 JS 非同步處理概念 @ PJCHENder blog
fetch(endpoint)
.then((blob) => blob.json()) // 取得 readableStream,並轉成 json 後 return
.then((data) => {
cities = data; // 把 data 代進去 cities 陣列中
console.log(cities); // 這裡可以取得資料
});