DEV Community


Discussion on: Understanding JavaScript async/await in 7 seconds

fervero profile image
Maciej Bójko

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

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

is an equivalent of

const getMoreDataButWrappedWithOneMoreFunction = x => getMoreData(x);

   .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.

wassimchegham profile image
Wassim Chegham Author

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:


emptyother profile image

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.