proposal-async-do-expressions icon indicating copy to clipboard operation
proposal-async-do-expressions copied to clipboard

Explain why it's not already supported in do proposal

Open ecyrbe opened this issue 4 years ago • 4 comments

Please explain to us why you think it's needed to add the async keyword.
This should already work with the current do proposal. no need to add any async keyword.

const page = do {
  await fetch('https://www.google.com');
};
expect(page).toBeInstanceOf(Promise);

Indeed, do notation is context sensitive... using await in a do expression will require the caller to be an async function. it's transitive, it's implied by context.

ecyrbe avatar Feb 23 '21 23:02 ecyrbe

async do is usable even outside of async functions; indeed, that's a major motivation for it. (This works because it resolves to a promise, not a regular value, in the same way that invoking an async function resolves to a promise.) It also has the effect of "forking" control, so that something like

await Promise.all([
  async do {
    let x = await fetch('a');
    x.json();
  },
  async do {
    let x = await fetch('b');
    x.json();
  },
]);

would fetch both a and b in parallel.

bakkot avatar Feb 23 '21 23:02 bakkot

Also, your example is mistaken. With a regular do expression, page would not be a promise (because you've unwrapped the result with await).

bakkot avatar Feb 23 '21 23:02 bakkot

you are right, in the exemple, i would have needed to :

const page = do {
  const x = await fetch('https://www.google.com');
  x.json();
};
expect(page).toBeInstanceOf(Promise);

Thanks for the clarification.

So if the main purpose of this is to force the do expression to return a promise and not block, maybe you should explain it in the proposal as the intent was not clear to me.

Indeed, for just replacing one async IIFE (which is the main motivation example of this proposal), i think that the do proposal is sufficiant, but you are right that forking execution was not covered.

ecyrbe avatar Feb 24 '21 00:02 ecyrbe

for just replacing one async IIFE (which is the main motivation example of this proposal), i think that the do proposal is sufficiant

That proposal doesn't allow you to use await unless you're already in an async context. The point of this proposal is to introduce a new async context, particularly in cases where you aren't currently in one.

bakkot avatar Feb 24 '21 00:02 bakkot