首页 > 解决方案 > 为什么生成器的 es5 转译代码有一段时间(1)

问题描述

与 babel repl 一样,如果我们有类似的 es6 代码:

function* test() {

  let a = yield 1
  let b = yield 2
}

它将被编译成

"use strict";

var _marked =
  /*#__PURE__*/
  regeneratorRuntime.mark(test);

function test() {
  var a, b;
  return regeneratorRuntime.wrap(function test$(_context) {
    while (1) {
      switch ((_context.prev = _context.next)) {
        case 0:
          _context.next = 2;
          return 1;

        case 2:
          a = _context.sent;
          _context.next = 5;
          return 2;

        case 5:
          b = _context.sent;

        case 6:
        case "end":
          return _context.stop();
      }
    }
  }, _marked);
}

只是无法理解生成代码中while(1)的目的是什么(如在case部分中,它使用return,它会跳出while(1)并且如果while(1)生效,整个 Javascript 线程都将被占用,无法进行其他操作)

标签: generatorbabeljs

解决方案


推荐阅读