Skip to content

Instantly share code, notes, and snippets.

@maxpowa
Last active June 25, 2019 22:29
Show Gist options
  • Save maxpowa/cfd4954766a74fd1db95985e67bf8a86 to your computer and use it in GitHub Desktop.
Save maxpowa/cfd4954766a74fd1db95985e67bf8a86 to your computer and use it in GitHub Desktop.

Fun regenerator-runtime facts

So lets start with something that works as expected.

const foo = async () => {
  throw new Error();
};

const bar = async () => {
  try {
    const res = await foo();
    return res;
  } catch (err) {
    // will catch the error!
  }
};

await bar();

regenerator-runtime turns this into (simplified)

new Promise().then(foo).catch(noop);

Right? Everything is cool, regenerator-runtime works great. WRONG!!

const foo = async () => {
  throw new Error();
};

const bar = async () => {
  try {
    return foo();
  } catch (err) {
    // won't catch anything!
  }
};

await bar(); // this will throw ._.

regenerator-runtime turns this into

new Promise().catch(noop).then(foo);

Why?

One returns the promise and the other returns the result of the promise.

This makes NO sense though! Why would you ever want this behavior, especially since it differs from native behavior so much!? Let's look at some native, non-async examples...

Non-async/await

const foo = () => {
  throw new Error();
};

const bar = () => {
  try {
    return foo();
  } catch (err) {
    // catches, duh
  }
};

bar();
const foo = () => {
  throw new Error();
};

const bar = () => {
  try {
    const res = foo();
    return res;
  } catch (err) {
    // catches, duh
  }
};

bar();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment