babel工具插件下载:npm i --save babel-polyfill
引入:polyfill.js进行转码(es8->es5)
介绍
- Generator函数用于生成迭代器
function * (){}
- yeild: 作用同return类似
{ const obj = function* () { yield "a"; yield 123; }; const fn = obj(); console.log(fn.next()); // {value: 'a', done: false} console.log(fn.next()); console.log(fn.next()); // {value: undefined, done: true} }
使用场景
- 遍历对象属性
{
let obj = {
name: "jacak",
age: 15,
phone: 12345678,
};
obj[Symbol.iterator] = function* () {
for (const key of Object.keys(obj)) {
yield obj[key];
}
};
for (const val of obj) {
console.log(val); // jacak 15 12345678
}
}
- 保持有限个状态
{
const status = function* () {
while (1) {
yield "success";
yield "fail";
yield "waiting";
}
};
let fn = status();
console.log(fn.next());
console.log(fn.next());
console.log(fn.next());
console.log(fn.next());
console.log(fn.next());
}
- 自动查询支付状态
// 查询支付状态
function payState() {
return new Promise((res) => {
setTimeout(() => {
console.log("正在查询...");
res({ code: -1 });
}, 1000);
});
}
// generator迭代,获取支付状态
const getPayState = function* () {
yield payState();
};
function autoQuery() {
const it = getPayState();
const state = it.next();
state.value.then((res) => {
if (res.code == 0) {
console.log("支付成功");
} else {
console.log("支付失败...");
setTimeout(() => autoQuery(), 500);
}
});
}
autoQuery();
- 可以使异步任务按照同步顺序执行
{
const ajax = function* () {
console.log("任务开始");
yield function (fun) {
setTimeout(() => {
console.log("异步任务执行");
fun && fun();
}, 2000);
};
};
let fn = ajax();
let sn = fn.next();
sn.value(() => fn.next());
}