這是我在github 上發(fā)現(xiàn)的一個原生js挑戰(zhàn)項目,由于是js小白,希望通過這次的項目加深對js的理解
第六天的挑戰(zhàn)是在輸入框中輸入關鍵字,迅速匹配,展示含有關鍵字的城市,json數據是從網絡中異步獲得的。
效果圖如下:

const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities = [];
fetch(endpoint)
.then(blob => blob.json())
.then(data => {console.log(data);cities.push(...data);});
涉及的新特性:
- promise 可以參考阮一峰的ES6 教程,這是ES6的新特性
- fetch()
- then
- RegExp
- match():查找匹配的地名
- replace():替換
const matchArray = findMatches(this.value, cities);
const html = matchArray.map(place => {
const regex = new RegExp(this.value, 'gi');
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${numberWithCommas(place.population)}</span>
</li>
`;
}).join('');
suggestions.innerHTML = html;
}
今天的重點是粗略地學習一下fetch()和promise
Promise 是異步編程的一種解決方案,比傳統(tǒng)的解決方案——回調函數和事件——更合理和更強大。它由社區(qū)最早提出和實現(xiàn),ES6 將其寫進了語言標準,統(tǒng)一了用法,原生提供了Promise對象。
Promise 有三個狀態(tài)
- pending : 初始化狀態(tài),沒有完成或拒絕
- fulfilled: 操作成功完成
- rejected: 操作失敗
Promise有兩種狀態(tài)改變的方式,既可以從pending轉變?yōu)閒ulfilled,也可以從pending轉變?yōu)閞ejected。一旦狀態(tài)改變,就「凝固」了,會一直保持這個狀態(tài),不會再發(fā)生變化。當狀態(tài)發(fā)生變化,promise.then綁定的函數就會被調用。
then(onFulfilled, onRejected):這個方法實際上是把onFulfilled()函數和onRejected()函數添加到Promise對象的回調鏈中?;卣{鏈就像一個由函數組構成的隊列,每一組函數都是由至少一個函數構成(onFulfilled() 或者 onRejected() 或者 onFulfilled() 和 onRejected())。當resolve()或者reject()方法執(zhí)行的時候,回調鏈中的回調函數會根據PromiseStatus的狀態(tài)情況而被依次調用。

傳統(tǒng) Ajax 指的是 XMLHttpRequest(XHR),將來會被 Fetch 替代。
使用XMLHttpRequest發(fā)送一個json
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = function() {
console.log(xhr.response);
};
xhr.onerror = function() {
console.log("錯誤");
};
xhr.send();
使用fetch()
fetch(url)
.then(request => request.json)
.then(data => console.log(data))
.catch(console.log("錯誤"));
fetch()的代碼明顯簡潔了很多,api的使用可以參考MDN
以上就是我在day6中學到的知識,這里我同樣參考了soyaine的中文指南,感謝