傳統(tǒng)異步
- 回調(diào)函數(shù)
- 響應(yīng)事件
- 發(fā)布/訂閱
- Promise
Generator 異步案例
適用場景,執(zhí)行a任務(wù),暫停a任務(wù),執(zhí)行b任務(wù),執(zhí)行完畢之后繼續(xù)執(zhí)行a任務(wù)
function fetchData(url) {
let data = yield fetch(url)
// 對數(shù)據(jù)進(jìn)行操作
console.log(data)
}
let f = fetchData("http://www.nini.com")
let resultIterator = f.next()
resultIterator.value.then(function (response) {
return response.json()
}).then(function (data) {
f.next(data)
})
知識點補(bǔ)充
- fetch 將返回一個promise對象
- 只要網(wǎng)絡(luò)不出錯,就會成功
-
response會作為響應(yīng)成功的參數(shù),和data是不同的 - 使用
response.json()取出body中的數(shù)據(jù),body的類型多種多樣,所以取數(shù)據(jù)也有很多的方式