Does async/await solve a real problem?

Tab Atkins Jr. jackalmage at gmail.com
Fri Sep 12 09:44:50 PDT 2014


On Fri, Sep 12, 2014 at 8:14 AM, C. Scott Ananian <ecmascript at cscott.net> wrote:
> On Fri, Sep 12, 2014 at 2:24 AM, Florian Bösch <pyalot at gmail.com> wrote:
>> It's often the case that the code which uses the async code, uses other
>> code, which isn't authored by the author, and isn't documented for await
>> compatibility. For instance:
>>
>> $.each(somelist, async function(item){
>>     await Foobar(item);
>> });
>>
>> Suppose $ is jQuery, is this async safe? Google for jQuery documentation
>> and/or read code.
>>
>
> I don't think this example is valid.  As I understand it, `async
> function` is a function that returns a promise.  You don't have to
> look into the library at all, it's just a normal value-returning
> function from its perspective.  I think your example should have been
> something like:
>
> `await Promise.all($.map(somelist, async function(item) { await
> Foobar(item); })`.
>
> But I'm not 100% up-to-speed on the await/async proposal.  Hopefully
> someone will correct me if I've gotten this wrong.  The bottom line
> should be that atomicity boundaries are explicitly noted with
> await/async; for library code which does not expose an 'async' marker
> you are guaranteed that it will execute atomically.  In this
> particular example this just means that all the promises created by
> the `async function` will be created atomically and execution returned
> to the called *before* any of the bodies of the `async function`s are
> run.
>
>> somelist.each(async function(item){
>>   await Foobar(item);
>> });
>>
>> Has the browser made his each function async safe? Google for JS API
>> documentation of the browser and/or start reading the source code of the
>> browser (really?).
>
> This is exactly the same as the jquery example.  No
> implementation-introspection needed.

You've got it right.  `async function` solely makes the function
return a Promise for its return value, rather than returning its
return value normally; nothing magical goes on beyond that.  There's
absolutely no need to check if a function is "async-safe" or propagate
an `async` on all functions up the call chain; you can just call the
function normally and receive a Promise.  You only need to make
yourself `async` if you want to consume the value of an async function
call directly, without having to go through the Promise indirection
manually.

Browsers will likely optimize cases where an async function call is
immediately consumed by an await expression and do some pipelining or
something, but that's behind-the-scenes optimization.

~TJ


More information about the es-discuss mailing list