Generator异步函数

Document

2020-09-21
Generator异步函数
用法:
结合 co 执行器 可以模拟async await 函数的实现
 
function ajax(url) {
  return new Promise((resolve, reject) => {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = () => {
      if (xhr.status === 200) resolve(xhr.response);
      else reject(new Error(xhr.statusText));
    }
    xhr.send();
  })
}

// 生成器函数 + co 执行器 就是async await的一种实现
function* main() {
  try {
    const person = yield ajax('./part1/person.json');
    console.log(person, 1);
    const person2 = yield ajax('./part1/person2.json');
    console.log(person2, 2);
    const person3 = yield ajax('./part1/person2.json');
    console.log(person3, 3);
  } catch (error) {
    console.log(error);
  }
}

// 生成器函数执行器
function co(generator) {
  const g = generator();
  function handler(result) { // 生成器函数的执行器
    if (result.done) return; // 如果传入的生成器函数的done已经为true了 说明执行完了
    result.value.then(data => { // 如果没有 那么result的value应该是一个promise对象
      handler(g.next(data)); // 拿到数据后继续调用next把数据传入 并且再次递归handle
    }, error => {
      g.throw(error); // 如果有错误 直接throw一个错误给生成器 那么在生成器内部的catch中就可以捕获这个错误
    });
  }
  handler(g.next());
}

co(main);
async function main() {
  try {
    const person = await ajax('./part1/person.json');
    console.log(person, 1);
    const person2 = await ajax('./part1/person2.json');
    console.log(person2, 2);
    const person3 = await ajax('./part1/person2.json');
    console.log(person3, 3);
  } catch (error) {
    console.log(error);
  }
}

 

posted @ 2020-09-21 22:03  蓝小胖纸  阅读(148)  评论(0编辑  收藏  举报