Hacker News new | ask | show | jobs
by peferron 1096 days ago
> I have some code here, and when exactly is this run?

If there are `await` keywords previously in the function, then the line you're looking at will run after these async calls are done. Otherwise it'll run ASAP. Is there something else to it?

1 comments

People often get confused because they expect `await` to sequence promise resolution too. For example

    const example = async () => {
        const ifError = Promise.reject("something went wrong")
        const value = await someOtherPromise()
        await (valueIsOk(value) ? runNextStep(value) : ifError)
    }
will always throw.
I don't think I follow. Your example left out all the definitions of these functions, so you can't really deterministically say what will happen. If `someOtherPromise()` fulfills, `valueIsOk(value)` evaluates to `true` or truthy, and `runNextStep(value)` fulfills, `example` will fulfill and not reject. If any of those conditions don't hold, `example` settles as rejected.
The issue is that `ifError` throws whether `example` fulfills or not. Promised values are sequenced by `async`, but promise side-effects are sequenced like side effects of any other javascript statement.
Sure, ifError rejects, but I don't think the behavior here is surprising or strange at all. This is exactly how one would want it to work. If you wanted to await it, you could do that.

Is the concern you're raising that people may accidentally orphan floating promises? That can be addressed with linter rules. [1][2]

[1]: https://github.com/typescript-eslint/typescript-eslint/blob/...

[2]: https://github.com/typescript-eslint/typescript-eslint/blob/...

> but I don't think the behavior here is surprising or strange at all.

Tell that to my junior coworkers. It's probably the single most common cause of async bugs in our codebase.

Are you running those two lint rules I mentioned? They should completely remove cases of accidental floating promises.