Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active April 14, 2022 15:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save WebReflection/e77838e233d56307d8b66a1332a41fd5 to your computer and use it in GitHub Desktop.
Save WebReflection/e77838e233d56307d8b66a1332a41fd5 to your computer and use it in GitHub Desktop.

async / return await explained

This is yet another explanation of why async and return await is pointless, coming from this post.

// async means that this:
const fn = async (...args) => {/* stuff */};

// is basically the equivalent of this:
const fn = (...args) => new Promise(resolve => {
  // async wraps the original callback as Promise
  const original = (...args) => {/* stuff */};
  // and resolves it
  resolve(original(...args));
  // if an error is thrown and no try/catch
  // is around, it breaks outer execution
});

// await means that this:
const val = await fn();

// is basically the equivalent of this:
Promise.resolve(fn()).then(result => {
  // the program pauses until result is known
  // and it keeps executing with val as result
  const val = result;
  // if fn() throws an error and no try/catch
  // is around, it breaks outer execution
});


// so that this:
const fn = async any => await any;

// is the equivalent of this
const fn = any => new Promise(resolve => {
  const original = any => Promise.resolve(any);
  //                      ^^^^^^^^^^^^^^^
  original.then(resolve);
  //            ^^^^^^^
  // can you see that there are 2 resolves for
  // the exact same value?
});

// that means that this:
const fn = async any => any;

// becomes this:
const fn = any => new Promise(resolve => {
  const original = any => any;
  resolve(original(any));
});

// and that's *all* we need, anything else
// is unnecessary overhead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment