Skip to content

Instantly share code, notes, and snippets.

@mattdanielbrown
Forked from WebReflection/async-await.md
Created December 14, 2021 18:34
Show Gist options
  • Save mattdanielbrown/6e3f141edf5444c529ae529b783a3095 to your computer and use it in GitHub Desktop.
Save mattdanielbrown/6e3f141edf5444c529ae529b783a3095 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