If you're modifying a non-async method used in a lot of places, and you find you need to work with a promise inside it, it's much easier to just pass it callbacks than to make the method async and refactor every place where it's called.
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.
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:
It buries your dependencies, so reading the function signature doesn't tell you what is coming into the function.
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.
Don’t listen to this person! Asynchronous/await is a promise and if you start throwing async/await without knowing how promises work, you’re going to have blowups.
10
u/amdc !CURSED! May 28 '19
knowing Promises is essential if you want to succeed, but once you're familiar with them you should move on to async/await