Search code examples
typescriptpromiseasync-awaittype-safety

How to correctly await a promise in TypeScript


I have some code where I continue a loop if a promise rejects or use its result with something that requires it to be of the reolved type, as shown in the following example code:

for (const i in bar) {
    let error = false;
    const foo = await somePromise(i)
        .catch(() => { error = true; });
    if (error) continue;
    // Something that requires foo to be resolved here
}

My issue is that typescript does not realize that foo is correctly resolved at the end (it still thinks it could be void due to not correctly resolving, and therefore gives a 2339 error). What is the correct, type-safe way to have typescript realize that this is fine?

The ways I have found to fix it are by stating that foo is of type any, which is not ideal and my linter doesn't like that, or using .then, which also sucks since I'd have to start nesting multiple .then statements and functions in my code, leading to massive indentations.


Solution

  • I would recommend

    for (const i in bar) {
        try {
            const foo = await somePromise(i)
            // Something that requires foo to be resolved here
            // break???
        } catch {
            continue
        }
    }
    

    or indeed then, which isn't that ugly and doesn't need more indentation (or even nesting) either:

    for (const i in bar) {
        const error = await somePromise(i).then(foo => {
            // Something that requires foo to be resolved here
            return false;
        }, err => {
            return true;
        });
        if (!error) {
            // break???
        }
    }