Building on async functions and the not-formally-proposed "do expressions", "async do expressions" let you write asynchronous blocks in an expression context, returning the completion value (a Promise).
This is useful when functions expect an asynchronous result (a Promise) as input, and the steps to produce that result can be expressed in line with the function call.
Example:
fetchEvent.respondWith(async {
var response = await fetch('https://example.com/resource');
var body = await response.text();
'BEGIN---\n' + body + '\n---END\n';
});
This is similar to an "immediately invoked async function expression", i.e.:
fetchEvent.respondWith((async () => {
var response = await fetch('https://example.com/resource');
var body = await response.text();
return 'BEGIN---\n' + body + '\n---END\n';
})());
Or more verbosely:
async function f() {
var response = await fetch('https://example.com/resource');
var body = await response.text();
return 'BEGIN---\n' + body + '\n---END\n';
};
let p = f();
fetchEvent.respondWith(p);
PrimaryExpression :
...
AsyncBlockExpression
AsyncBlockExpression :
"async" [no LineTerminator here] Block
ExpressionStatement :
[lookahead ∉ {{, function, class, let [, async}] Expression;
TODO - static and runtime semantics
var
hoisting behavior needs definitionbreak
,continue
andreturn
need definition
- async functions
- do expressions strawman
- TC39 meeting notes: Do Expression
- es-discuss thread: monadic extension to do-notation