<script>
//三個ajax異步的請求要保證執(zhí)行的順序
//1. 傳統(tǒng)的callback觸發(fā)回調(diào)地獄 痛苦 處理異步任務按照順序 異步-->同步化執(zhí)行 代碼的可讀性更好
//2. promise then then語義化明顯
//3.Generator生成函數(shù)
//4.async await
//ajax函數(shù) xhr
//XHR代表 "XMLHttpRequest",是一種用于在Web瀏覽器和服務器之間發(fā)送HTTP請求和接收響應的API。它是一種基于事件驅(qū)動的技術,允許客戶端通過JavaScript與服務器進行異步通信,而無需刷新整個頁面。
//通過使用XHR對象,開發(fā)者可以發(fā)送各種類型的HTTP請求,例如GET、POST和PUT等。XHR還支持異步請求,這意味著瀏覽器可以在等待服務器響應時繼續(xù)執(zhí)行其他操作,而不會阻塞用戶界面
// function ajax(url, fn) {
// let xhr = new XMLHttpRequest();
// xhr.open('GET', url);
// xhr.onreadystatechange = function() {
// ///4請求完全到達的狀態(tài)并且請求成功的狀態(tài)
// if (xhr.readyState === 4 && xhr.status == 200) {
// fn(JSON.parse(xhr.responseText))
// }
// }
// xhr.send()
// }
// ajax('https://api.github.com/users/wesbos', function(result) {
// console.log(result);
// ajax('https://api.github.com/users/wesbos', function(result) {
// console.log(result, '222');
// ajax('https://api.discogs.com/artists/51988', function(result) {
// console.log(result, '333');
// })
// })
// })
//假如有這么一個函數(shù)async()=》{}
//不止執(zhí)行一次
//生成器函數(shù)Generator function(async出現(xiàn)之前出現(xiàn)過,僅作為了解)
//"yield" 這個關鍵字通常用于生成器函數(shù)或異步操作中,生成器函數(shù)可以通過 "yield" 關鍵字來暫停執(zhí)行并向調(diào)用者返回一個值,而不是一次性執(zhí)行完整個函數(shù)。這在處理需要逐步獲取結果的異步操作或大量數(shù)據(jù)時非常有用。
function* foo(x){
console.log('1');
yield x+1 //返回,記錄下執(zhí)行狀態(tài)
console.log('2');
yield x+2
console.log('3');
return x+3
}
let steps = foo(1)//執(zhí)行器 ,通過調(diào)用next()方法來逐步獲取生成器函數(shù)中產(chǎn)生的值
// console.log(steps.next());
// console.log(steps.next());
// console.log(steps.next());
// console.log(steps.next());
//或者使用以下es6的方法
for(let x of steps){
console.log(x );
}
</script>
運行結果:
ok,投入實踐文章來源地址http://www.zghlxwxcb.cn/news/detail-832462.html
//這個寫法解決promise回調(diào)地獄的問題
function ajax(url) {
fetch(url) //promise二進制流
.then(data => data.json()) //promise將響應的二進制流轉(zhuǎn)換為 JSON 格式,返回一個新的 Promise 對象
.then(data => dataGen.next(data))//將獲取到的數(shù)據(jù)傳遞給生成器函數(shù)中的下一個 yield 語句
}//自動調(diào)用next方法了
function* steps() { //生成器函數(shù)
console.log('fetching beers');
const beers = yield ajax('https://api.github.com/users/wesbos')
console.log(beers);
const wes = yield ajax('https://api.github.com/users/wesbos')
console.log(wes);
const fatJoe = yield ajax('https://api.discogs.com/artists/51988')
console.log(fatJoe);
}
const dataGen = steps()
dataGen.next();
文章來源:http://www.zghlxwxcb.cn/news/detail-832462.html
到了這里,關于Generator生成器函數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!