r/javascript • • May 28 '19

What are some JavaScript things beginners don't know?

333 Upvotes

383 comments sorted by

View all comments

Show parent comments

1

u/[deleted] May 31 '19

That's a horrible, and unfortunately very common, take. Once you're famiar with promises, you should just stick to the functional/declarative path and generally forget that async/await exists.

1

u/amdc !CURSED! May 31 '19

Why though?

1

u/[deleted] Jun 01 '19

There are so many reasons to avoid async/await, and practically zero for using it. Without going into every advantage of a pure-functional approach...

Think about how you'd get a promise into a function to need awaiting in the first place. I think the most common, because it's basically what async/await was designed to allow bad programmers (let's be real, Java programmers) to do is to call an asynchronous function within another function. Something like this:

const fun = async () => {
  const input = await someAsyncFunc()

  /* do whatever with input to get the result */

  return result  
}

A couple of obvious reasons you don't want to do something like this:

  1. It buries your dependencies, so reading the function signature doesn't tell you what is coming into the function.

  2. It makes testing the function more difficult.

The other reasons are more or less obvious, depending on your familiarity with pure-functional programming.

By moving the input into the function parameters, you can alleviate both of these obvious problems.

const fun = async (input) => {
  /* do whatever by "awaiting" input to get the result */

  return result
}

fun(someAsyncFunc())

OK, but now you're passing in the promise returned from someAsyncFunc() as the input of your function. I wouldn't say you'd never want to pass a promise into a function, but I wouldn't argue with someone who did say that.

When you take a promise as input to your function, you're requiring your function to understand and deal with the promise-wrapped value, when all you really want is the value. You're adding complexity and an implicit dependency to the function for no gain.

So drop that dependency by just having your function take the input value directly.

const fun = (input) => {
  /* do whatever with input to get the result */

  return result
}

someAsyncFunc().then(fun)

The then() method will pass the value into fun() as input and then wrap the returned result in a promise for whatever you want to chain on after it. The function doesn't have to know anything about promises.