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);
      }
    }
  • 相关阅读:
    1042 Shuffling Machine
    1043 Is It a Binary Search Tree
    1044 Shopping in Mars
    1443. Minimum Time to Collect All Apples in a Tree
    1045 Favorite Color Stripe
    Java笔记八:Java内置的包装类(1)
    Java笔记七:Java数字和日期处理(2)
    Java笔记六:Java数字和日期处理(1)
    Java笔记五: Java正则表达式
    Java笔记四:Java字符串处理
  • 原文地址:https://www.cnblogs.com/lanpang9661/p/13709046.html
Copyright © 2011-2022 走看看