DEV Community

Discussion on: Understanding JavaScript async/await in 7 seconds

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.