V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
rabbbit
V2EX  ›  问与答

面试官问:为什么说 async/await 是生成器的语法糖?这种题一般需要掌握到什么深度?

  •  
  •   rabbbit · 2022-03-06 16:16:24 +08:00 · 530 次点击
    这是一个创建于 795 天前的主题,其中的信息可能已经有所发展或是发生改变。

    没答上,我连生成器语法是啥都忘了.这种题一般需要讲到什么深度呢?
    我的理解就是 async 能实现的 Generator 也全都能做到,只是 async 写起来更方便(顾名思义, 糖呗).😞

    第 1 条附言  ·  2022-03-06 16:58:11 +08:00

    补一个 Generator 实现 async/ await

    function prom() {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve("success");
        }, 1000);
      });
    }
    function* gene() {
      const num = yield 1;
      console.log(num); // 1
      const result = yield prom();
      console.log(result); // success
    }
    
    function run(gene) {
      let g = gene();
      function next(value) {
        let result = g.next(value);
        return result.done
          ? result.value
          : typeof result.value?.then === 'function'
            ? result.value.then((value) => next(value))
            : Promise.resolve(result.value).then((value) => next(value))
      }
      next();
    }
    
    run(gene);
    
    
    rabbbit
        1
    rabbbit  
    OP
       2022-03-06 16:38:53 +08:00
    想了一下,无非就是:
    1 什么是语法糖
    2 async/await 是做什么的,怎么用
    3 Generator 是做什么的,怎么用
    4 如何用 Generator + Promise 实现 async/await

    没啥可问的,沉了.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3743 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 10:44 · PVG 18:44 · LAX 03:44 · JFK 06:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.