function*
模拟 async
yield
模拟 await
简单模式:yield
后边只能跟着 promise
,且不进行异常处理
function asyncFunc(){
function run(_genFunc){
return new Promise(resolve=>{
let gen = _genFunc();
function next(_data){
let result = gen.next(_data);
if(result.done) resolve(result.value);
else result.value.then(next);
}
next();
})
}
return run(function *(){
let r1 = yield new Promise(resolve=>{
setTimeout(()=>{
resolve(1);
}, 1000)
})
console.log(r1);
let r2 = yield new Promise(resolve=>{
setTimeout(()=>{
resolve(2);
}, 1000)
})
console.log(r2)
return 3;
})
}
asyncFunc().then((_data)=>{
setTimeout(()=>{
console.log(_data)
}, 1000)
})