ES2017 - Async vs. Yield

前端 未结 4 1511
囚心锁ツ
囚心锁ツ 2020-12-05 12:59

I am confused about the current discussion of adding async functions and the keyword await to the next EcmaScript.

I do not understand why it is necessa

4条回答
  •  醉酒成梦
    2020-12-05 13:56

    I do not understand why it is necessary to have the async keyword before the function keyword.

    For the same reason that we have the * symbol before generator functions: They mark the function as extraordinary. They are quite similar in that regard - they add a visual marker that the body of this function does not run to completion by itself, but can be interleaved arbitrarily with other code.

    • The * denotes a generator function, which will always return a generator that can be advanced (and stopped) from outside by consuming it similar to an iterator.
    • The async denotes an asynchronous function, which will always return a promise that depends on other promises and whose execution is concurrent to other asynchronous operations (and might be cancelled from outside).

    It's true that the keyword is not strictly necessary and the kind of the function could be determined by whether the respective keywords (yield(*)/await) appear in its body, but that would lead to less maintainable code:

    • less comprehensible, because you need to scan the whole body to determine the kind
    • more errorprone, because it's easy to break a function by adding/removing those keywords without getting a syntax error

    a normal function, whose execution will wait for finishing the hole body until all awaits are fulfilled

    That sounds like you want a blocking function, which is a very bad idea in a concurrent setting.

提交回复
热议问题