JavaScript Generator 和 Promise 使异步变同步

JavaScript Generator 和 Promise 使异步变同步

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

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}

发表评论

请先登陆

  1. bucai

    Thu Oct 03 2019 11:16:55 GMT+0800 (GMT+08:00)

    test
    回复