rabbbit
V2EX  ›  问与答

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

  •  
  •   rabbbit · Mar 6, 2022 · 929 views
    This topic created in 1544 days ago, the information mentioned may be changed or developed.

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

    Supplement 1  ·  Mar 6, 2022

    补一个 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
       Mar 6, 2022
    想了一下,无非就是:
    1 什么是语法糖
    2 async/await 是做什么的,怎么用
    3 Generator 是做什么的,怎么用
    4 如何用 Generator + Promise 实现 async/await

    没啥可问的,沉了.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3235 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 13:13 · PVG 21:13 · LAX 06:13 · JFK 09:13
    ♥ Do have faith in what you're doing.