Learning about async/await

When writing async functions, there are differences between await vs return vs return await, and picking the right one is important.

April 03, 2019

Should you return await async javascript functions? In simple terms, seldom:

Since the return value of an async function is always wrapped in Promise.resolve, return await doesn’t actually do anything except add extra time before the overarching Promise resolves or rejects.

I have been developing with Javascript for a couple of years and I still learn things. When you write async functions it is important to remember what you return. When we look at the following async function we see that after 2 seconds it returns 'Foo'.

async function foo() {
  const msg = await new Promise((resolve) => {
    setTimeout(() => {
      resolve("Foo");
    }, 2000);
  });
  console.log("Message:", msg);
}

msg(); // Message: 'Foo' <-- after 2 seconds

When using async/await instead of Promise you should always use a try/catch. Below we don't use await and so the returned promise will always fulfill with undefined, without waiting.

async function printFooAfterTwoSeconds() {
  try {
    foo();
  } catch (e) {
    return "caught";
  }
}
async function printFooAfterTwoSeconds() {
  try {
    await foo();
  } catch (e) {
    return "caught";
  }
}
async function printFooAfterTwoSeconds() {
  try {
    return foo();
  } catch (e) {
    return "caught";
  }
}
async function printFooAfterTwoSeconds() {
  try {
    return await foo();
  } catch (e) {
    return "caught";
  }
}

Outside of try/catch blocks, return await is redundant. There's even an ESLint rule to detect it, but it allows it in try/catch.

Tagged with javascript

Software Development

  • Cloud computing, microservices, APIs, full stack web apps
  • Hybrid mobile apps with Flutter

Technologies

  • JS&TS (React/Vue/Svelte)
  • PHP (Laravel)
  • Java/Kotlin
  • GoLang

Future Ventures (Teach myself in 2020)

  • Scalable distributed systems (infrastructure, networks, microservices, kubernetes)
  • Creating mobile applications in Flutter
  • Working more with Graphql
  • Become better at solving algorithmic problems.

Projects currently working on

  • Scrum application in React/Go with Graphql
  • Seedbox in Kubernetes
  • A recipe webapp for the secret recipes of my family
  • CRM application with Laravel/TailwindCSS/Livewire/AlpineJS
  • Learning to be a better writer
© Copyright - 2020 - Source on github- Built on August 26th, 2020