DEV Community

Discussion on: Understanding JavaScript async/await in 7 seconds

Collapse
 
fervero profile image
Maciej Bójko • Edited

To this day, I fail to see the wisdom of writing b => getMoreData(b), when mere getMoreData means exactly the same thing. Because really

getData()
  .then(a => getMoreData(a)) // repeat four times

is an equivalent of

const getMoreDataButWrappedWithOneMoreFunction = x => getMoreData(x);

getData()
   .then(getMoreDataButWrappedWithOneMoreFunction) // repeat four times

What is the point of getMoreDataButWrappedWithOneMoreFunction, I wonder? Why not just put getMoreData there?

It seems as if the moment a developer learn that in JS he can define a function in the middle of some expression, he immediately forgets he isn't obliged to.

Collapse
 
wassimchegham profile image
Wassim Chegham

Hey Maciej, thanks for reaching out.

So to give you some context, the code sample in the animation is meant to be easy for beginners to understand and it is not supposed to be too clever. So this was done on purpose in order to show the flow of all the parameters.

However, if you still prefer passing function references instead of function invocations, I have already made another animation illustrating this:

Cheers.

Collapse
 
emptyother profile image
emptyother

We still need to wrap the method in an arrow function to keep this in the correct context, unfortunately.

class myClass {
    myPrivateVal = "appendedValue";
    appendMyPrivateVal(argument) {
        return argument + ' ' + this.myPrivateVal;
    }
}
async function someAsyncMethod() {
    return new Promise<string>((resolve) => setTimeout(() => resolve("asyncResult"), 1000));
}
var myInstance = new myClass();
(async () => {
    const result = someAsyncMethod().then(myInstance.appendMyPrivateVal);
    result; // asyncResult undefined 
    const result2 = someAsyncMethod().then((arg) => myInstance.appendMyPrivateVal(arg));
    result2; // asyncResult appendedValue
})();

I really hate this sometimes.