JavaScript Generator 和 Promise 使异步变同步

不才
2019-09-21 08:31:09

<span style="">JavaScript Generator 和 Promise 使异步变同步</span>

Generator

function* gen() {
  yield console.log(1)
  yield console.log(2)
  console.log(3)
}
const g = gen()
g.next()
g.next()
g.next()
// 输出
// 1
// 2
// 3

Promise

function delay(ms) {  
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms);
  });
}
console.log(1)
delay(300).then(() => console.log(2))
console.log(3)
// 输出
// 1
// 3
// 2

Generator + Promise<span style="">
</span>

function* gen() {
  const data = yield new Promise((resolve, reject)=>{
        setTimeout(function(){
            resolve({a:1,b:2});
        },1000);
	});
  console.log(data)
}
const g = gen();

const {value} = g.next();
// 判断 Promise
if(value instanceof Promise){
value.then(data=>{
            // 执行 next 传递 data (next 可改成 send)
g.next(data);
});
}
// 输出
{a: 1, b: 2}