zoukankan      html  css  js  c++  java
  • 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);
      }
    }
  • 相关阅读:
    Sonne的健身日志(4)
    Sonne的健身日志(13)16周腹肌计划第四周(2012.3.302012.4.6)
    Sonne的健身日志(1)
    Iphone升级ios6后很耗电的解决办法
    试驾凯迪拉克SRX
    Sonne的健身日志(6)
    Sonne的健身日志(10)16周腹肌计划第一周感受与体会
    关于Iphone 4 如何用itunes备份短信等设置
    上海人2
    签了个100万的合同,我却很失落
  • 原文地址:https://www.cnblogs.com/lanpang9661/p/13709046.html
Copyright © 2011-2022 走看看