1 生成器函數(shù)
定義和使用生成器
生成器函數(shù)能生成一組值的序列雪位。顯式地向生成器請求一個新的值,隨后生成器響應(yīng)一個新生成的值奸忽,或者告訴我們它之后不會再生成新的值叠殷。
可以使用while
迭代生成器生成的值的序列改鲫,也可以使用for-of
語法糖。
function *DiningCar(){
yield '花生';
yield '瓜子';
yield '八寶粥';
}
const carIt=DiningCar();
let item;
while(!(item=carIt.next()).done){
console.log(item.value);
}
for(let item of DiningCar()){
console.log(item);
}
雙向通信
我們通過yield
語句從生成器中返回值林束,再使用迭代器的next
方法把值傳回生成器像棘。
function *DiningCar(user_name){
let count_peanuts=yield '花生';
let count_seed=yield '瓜子';
let count_congee=yield '八寶粥';
console.log('顧客姓名:'+user_name);
console.log('花生:'+count_peanuts);
console.log('瓜子:'+count_seed);
console.log('八寶粥:'+count_congee);
}
const carIt=DiningCar('bro bear');
carIt.next();//返回'花生'
carIt.next(1);
carIt.next(2);
carIt.next(3);
向生成器拋出異常
迭代器除了next
方法,還具有拋出一個異常的方法壶冒。
function *DiningCar(){
try{
yield '花生';
yield '瓜子';
yield '八寶粥';
}
catch(e){
console.log('交易失敗:'+e);
}
}
const carIt=DiningCar();
console.log(carIt.next());
carIt.throw('no enough money.');
2 promise
promise
對象是對我們現(xiàn)在尚未得到但將來會得到的值的占位符缕题。如果我們兌現(xiàn)了承諾,結(jié)果會得到一個值胖腾。如果發(fā)生了問題烟零,結(jié)果則是一個錯誤瘪松。
顯式接受/拒絕promise
var promise=new Promise((resolve,reject)=>{
resolve('23:00');
//reject('2:00');
})
promise.then(time=>{
console.log('sleep at '+time);
},time=>{
console.log('sleep at '+time);
});
異常隱式拒絕promise
var promise=new Promise((resolve,reject)=>{
sheep++;
})
promise.then(time=>{
console.log('sleep at '+time);
}).catch(()=>{
console.log('fail to sleep');
})
創(chuàng)建一個promise實例
promise
的一個最佳例子是從服務(wù)器獲取數(shù)據(jù)。我們要承諾最終會拿到數(shù)據(jù)锨阿,但總有可能發(fā)生錯誤宵睦。
function getJSON(url){
return new Promise((resolve,reject)=>{
const request=new XMLHttpRequest();
request.open('GET',url);
request.onload=()=>{
try{
if(this.status===200){
//解析json時可能發(fā)生異常
resolve(JSON.parse(this.response));
}
else{
//服務(wù)器響應(yīng)了其他代碼
reject(this.status+' '+this.statusText);
}
}
catch(e){
reject(e.message);
}
}
request.onerror=()=>{
//和服務(wù)器通信異常
reject(this.status+' '+this.statusText);
};
request.send();
});
}
getJSON('peanut.json').then(data=>{
console.log('we have peanuts!');
}).catch(e=>{
console.log('we have no peanuts!');
})
鏈式調(diào)用
處理多個有先后順序、相互依賴的異步任務(wù)墅诡。
getJSON('peanuts.json')
.then(getJSON('seeds.json'))
.then(getJSON('congee.json'))
.catch(error=>console.log('we have not enough food!'));
等待多個promise
處理多個獨立的異步任務(wù)壳嚎。
Promise.all
方法接收一個Promise數(shù)組,并創(chuàng)建一個新的promise
對象末早。當所有的promise
均成功時烟馅,該promise
為成功狀態(tài)。反之然磷,若其中任意一promise
失敗焙糟,則該promise
為失敗狀態(tài)。
Promise.all([getJSON('peanuts.json'),
getJSON('seeds.json'),
getJSON('congee.json')
]).then(results=>{
results.forEach(item=>console.log('we have'+item));
}).catch(error=>console.log('交易失斞馈!'+error));
promise競賽
Promise.race
方法接收一個Promise數(shù)組缺脉,并創(chuàng)建一個新的promise
對象痪欲。當某一個promise
被處理或被拒絕時,該promise
同樣會被處理或被拒絕攻礼。
Promise.race([getJSON('peanuts.json'),
getJSON('seeds.json'),
getJSON('congee.json')
]).then(results=>{
results.forEach(item=>console.log('we have'+item));
}).catch(error=>console.log('交易失斠堤摺!'+error));
3 生成器和promise相結(jié)合
不明覺厲
(async ()=>{
try{
const peanuts=await getJSON('peanuts.json');
const seeds=await getJSON('seed.json');
const congee=await getJSON('congee.json');
}catch(e){
console.log('Error:'+e);
}
})()