This is a proposal to allow async/await functions for general use in Chromium.
Feature:async/await functions
Overview:
async/await is a concise way to express asynchronous control flow as if they were synchronous.
Info:
Details:
Chaining together promises is tedious, especially when you have an asynchronous function that needs to be called multiple times in your control flow.
A common test pattern is to programmatically perform an operation, and then spin the message loop to allow rendering tasks to complete. This currently looks like this:
test('mytest', function() {
// Do thing 1.
MockInteractions.tap(button);
return PolymerTest.flushTasks()
.then(() => {
assertEquals(1, countDates());
// Do thing 2.
MockInteractions.tap(anotherButton);
return PolymerTest.flushTasks();
})
.then(() => {
assertEquals(4, countCards());
// Do thing 3.
MockInteractions.tap(button);
return PolymerTest.flushTasks();
})
.then(() => {
assertEquals(2, countDates());
});
});
The call to PolymerTest.flushTasks() essentially takes 3 lines each time, breaking apart the readable flow of code, and we have to add a bunch of boilerplate that is only necessary for the promise syntax.
With async/await, the code looks like this:
test('mytest', async function() {
// Do thing 1.
MockInteractions.tap(button);
await PolymerTest.flushTasks();
assertEquals(1, countDates());
// Do thing 2.
MockInteractions.tap(anotherButton);
await PolymerTest.flushTasks();
assertEquals(4, countCards());
// Do thing 3.
MockInteractions.tap(button);
await PolymerTest.flushTasks();
assertEquals(2, countDates());
});
The control flow better represents the logical grouping, and the
We also get more intuitive assignment and try/catch behavior:
try {
let text = await readFile('myFile.txt');
console.log(text);
} catch (err) {
alert(err);
}
vs
readFile('myFile.txt').then(
text => console.log(text)
).catch(err => alert(err));
Possible issues:
You can create unmanageable control flows with async/await, but these would be possible with promises too.
Compatibility:
Support in environments we care about (Chrome, iOS, node) looks good, as far as I can tell:
Tooling:
Supported in ESLint with 'parserOptions': { 'ecmaVersion': 2017 }.
Closure seems to handle it well. It knows that async functions return Promises, and complains if you have the wrong return type.
Uglify-ES needs a roll, but otherwise, adding an async function to Downloads works with optimize_webui = true.
tl;dr - What does everybody think?