abbr / deasync

Turns async function into sync via JavaScript wrapper of Node event loop
MIT License
971 stars 73 forks source link

[Bug] loop forever when using jest? #180

Open radiorz opened 1 year ago

radiorz commented 1 year ago

such as this


test("aa", async () => {
  function* yieldButNotAsync() {
    yield 1;
    yield 2;
    console.log(`end`);
  }
  async function asyncGenFunc() {
    // do something async
    console.log(`start`);
    const timeout = 2000;
    await new Promise((resolve) => setTimeout(resolve, timeout));
    return yieldButNotAsync.apply(this, arguments);
  }
  // 让他同步
  function synGenFunc() {
    let isDone = false;
    let result;
    asyncGenFunc.apply(this, arguments).then((iter) => {
      isDone = true;
      result = iter;
    });
    // 用 deasync 等待让他同步化
    require("deasync").loopWhile(function () {
      return !isDone;
    });
    return result;
  }

  (function () {
    const iter = synGenFunc();
    const value = iter.next();
    console.log(`value`, value);
    const value2 = iter.next();
    console.log(`value2`, value2);
  })();
});
radiorz commented 1 year ago

156 https://github.com/abbr/deasync/issues/156