• 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);
      }
    }
  • 相关阅读:
    入门OJ 1278【关系网络】
    HDU 1372【Knight Moves】
    ZOJ 1047【Image Perimeters】
    log4J——在Spring中的使用
    实用性很强的文章(不来源于博客园)
    详解AOP——用配置文件的方式实现AOP
    Spring与Web项目整合的原理
    IOC——Spring的bean的管理(注解方式)
    IOC——Spring的bean的管理(xml配置文件)
    关于XML文件
  • 原文地址:https://www.cnblogs.com/lanpang9661/p/13709046.html
Copyright © 2020-2023  润新知