Question about valid async syntax in TS/JS

Hello, I recently ran into a problem with some async web calls and Im trying to get to the root cause. I think I fixed it, but I want to learn more about how async works in TS/JS

​

I basically started with this code:

async function Function1(): Promise<void> {
    if(someCondition) {
        return Function2()    //NOTE: Im returning a promise without awaiting
    }
    await doWork();
}

async function Function2(): Promise<void>  => await work();

I later changed it to this code and my errors seem to be fixed:

async function Function1(): Promise<void> {
    if(someCondition) {
        await Function2();    //here I await the promise and return after
        return;
    }
    await doWork();
}

async function Function2(): Promise<void>  => await work();

I would like to know if the first example is valid JS or if I did correctly identify the issue. I know returning a promise from an async method like this is invalid in C#, but Im not sure about JS.

​

My follow up question: If this is invalid, why did TS not mark it as an error during compilation?

Posted Aug 12, 2022, 8:23 PM UTC

13
coolcosmos•

Nah, the first was valid. Not sure how changing the code how you did changed anything.

8

What error are you running into? The first one works

2
skarab42-dev•

Why do you want to await a promise and then do nothing? In fact your function returns a promise based on a condition, nothing more. The simplest form would be :

function workA(): Promise<void> { return Promise.resolve(); }
function workB(): Promise<void> { return Promise.resolve(); }

function doWork1(condition: boolean): Promise<void> { 
    return condition ? workA() : workB();
}

If your function needs to do another job before returning anything, then the await becomes util.

async function doWork2(condition: boolean): Promise<void> {
    if (condition) {
        const result = await workA(); // wait for long job to finish
        console.log(result); // Do somthing with the result!
        return; // Finally return, since the function is marked as async this is a Promise!
    }

    return workB(); // No need to await, juste return
}
2
[deleted]•

[deleted]

1