Proposal: Async Functions
Async Functions
1 Async Functions
This is a spec proposal for the addition of Async Functions (also known as async..await) as a feature of TypeScript.
2 Use Cases
Async Functions allow TypeScript developers to author functions that are expected to invoke an asynchronous operation and await its result without blocking normal execution of the program. This accomplished through the use of an ES6-compatible Promise implementation, and transposition of the function body into a compatible form to resume execution when the awaited asynchronous operation completes.
This is based primarily on the Async Functions strawman proposal for ECMAScript, and C# 5.0 § 10.15 Async Functions.
3 Introduction
3.1 Syntax
An Async Function is a JavaScript Function, Parameterized Arrow Function, Method, or Get Accessor that has been prefixed with the async modifier. This modifier informs the compiler that function body transposition is required, and that the keyword await should be treated as a unary expression instead of an identifier. An Async Function must provide a return type annotation that points to a compatible Promise type. Return type inference can only be used if there is a globally defined, compatible Promise type.
Example:
var p: Promise<number> = /* ... */;
async function fn(): Promise<number> {
var i = await p; // suspend execution until 'p' is settled. 'i' has type "number"
return 1 + i;
}
var a = async (): Promise<number> => 1 + await p; // suspends execution.
var a = async () => 1 + await p; // suspends execution. return type is inferred as "Promise<number>" when compiling with --target ES6
var fe = async function(): Promise<number> {
var i = await p; // suspend execution until 'p' is settled. 'i' has type "number"
return 1 + i;
}
class C {
async m(): Promise<number> {
var i = await p; // suspend execution until 'p' is settled. 'i' has type "number"
return 1 + i;
}
async get p(): Promise<number> {
var i = await p; // suspend execution until 'p' is settled. 'i' has type "number"
return 1 + i;
}
}
3.2 Transformations
To support this feature, the compiler needs to make certain transformations to the function body of an Async Function. The type of transformations performed depends on whether the current compilation target is ES6, or ES5/ES3.
3.2.1 ES6 Transformations
During compilation of an Async Function when targeting ES6, the following transformations are applied:
- The new function body consists of a single return statement whose expression is a new instance of the promise type supplied as the return type of the Async Function.
- The original function body is enclosed in a Generator Function.
- Any
awaitexpressions inside the original function body are transformed into a compatibleyieldexpression.- As the precedence of
yieldis much lower thanawait, it may be necessary to enclose theyieldexpression in parenthesis if it is contained in the left-hand-side of a binary expression.
- As the precedence of
- The Generator Function is executed and the resulting generator is passed as an argument to the
__awaiterhelper function. - The result of the
__awaiterhelper function is passed as an argument to the promise resolve callback.
Example:
// async.ts
var p0: Promise<number> = /* ... */;
var p1: Promise<number> = /* ... */;
async function fn() {
var i = await p0;
return await p1 + i;
}
// async.js
var __awaiter = /* ... */;
function fn() {
return new Promise(function (_resolve) {
_resolve(__awaiter(function* () {
var i = yield p0;
return (yield p1) + i;
}()));
});
}
3.2.2 ES5/ES3 Transformations
As ES5 and earlier do not support Generator Functions, a more complex transformation is required. To support this transformation, __generator helper function will be also emitted along with the __awaiter helper function, and a much more comprehensive set of transformations would be applied:
- The new function body consists of a single return statement whose expression is a new instance of the promise type supplied as the return type of the Async Function.
- The original function body is enclosed in a function expression with a single parameter that is passed as an argument to the
__generatorhelper function. - All hoisted declarations (variable declarations and function declarations) in the original function body are extracted and added to the top of the new function body.
- The original function body is rewritten into a series of case clauses in a switch statement.
- Each statement in the function body that contains an
awaitexpression is rewritten into flattened set of instructions that are interpreted by the__generatorhelper function. - Temporary locals are generated to hold onto the values for partially-applied expressions to preserve side effects expected in the original source.
- Logical binary expressions that contain an
awaitexpression are rewritten to preserve shortcutting. - Assignment expressions that contain an
awaitare rewritten to store portions left-hand side of the assignment in temporary locals to preserve side effects. - Call expressions that contain an
awaitin the argument list are rewritten to store the callee and this argument, and to instead call thecallmethod of the callee. - New expressions that contain an
awaitin the argument list are rewritten to preserve side effects. - Array literal expressions that contain an
awaitin the element list are rewritten to preserve side effects. - Object literal expressions that contain an
awaitin the element list are rewritten to preserve side effects. - try statements that contain an await in the try block, catch clause, or finally block are rewritten and tracked as a protected region by the
__generatorhelper function. - The variable of a
catchclause is renamed to a unique identifier and all instances of the symbol are renamed to preserve the block scope behavior of a catch variable. breakandcontinuestatements whose target is a statement that contains anawaitexpression are rewritten to return an instruction interpreted by the__generatorhelper function.returnstatements are rewritten to return an instruction interpreted by the__generatorhelper function.for..instatements that contain anawaitexpression are rewritten to capture the enumerable keys of the expression into a temporary array, to allow the iteration to be resumed when control is returned to the function following anawaitexpression.- Labeled statements that contain an
awaitexpression are rewritten. awaitexpressions are rewritten to return an instruction interpreted by the__generatorhelper function.
Example:
// async.ts
var p0: Promise<number> = /* ... */;
var p1: Promise<number> = /* ... */;
async function fn() {
var i = await p0;
return await p1 + i;
}
// async.js
var __awaiter = /* ... */;
var __generator = /* ... */;
function fn() {
var i;
return new Promise(function (_resolve) {
resolve(__awaiter(__generator(function (_state) {
switch (_state.label) {
case 0: return [3 /*yield*/, p0];
case 1:
i = _state.sent;
return [3 /*yield*/, p1];
case 2:
return [2 /*return*/, _state.sent + i];
}
}));
});
}
The following is an example of an async function that contains a try statement:
// async.ts
var p0: Promise<number> = /* ... */;
var p1: Promise<number> = /* ... */;
async function fn() {
try {
await p0;
}
catch (e) {
alert(e.message);
}
finally {
await p1;
}
}
// async.js
var __awaiter = /* ... */;
var __generator = /* .. */;
function fn() {
var i;
return new Promise(function (_resolve) {
resolve(__awaiter(__generator(function (_state) {
switch (_state.label) {
case 0:
_state.trys = [];
_state.label = 1;
case 1:
_state.trys.push([1, 3, 4, 6]);
return [3 /*yield*/, p0];
case 2:
return [5 /*break*/, 6];
case 3:
_a = _state.error;
alert(_a.message);
return [5 /*break*/, 6];
case 4:
return [3 /*yield*/, p1];
case 5:
return [6 /*endfinally*/];
case 6:
return [2 /*return*/];
}
}));
});
var _a;
}
As a result of these transformations, the JavaScript output for an Async Function can look quite different than the original source. When debugging the JavaScript output for an Async Function it would be advisable to use a Source Map generated using the --sourceMap option for the compiler.
4 Promise
Async Functions require a compatible Promise abstraction to operate properly. A compatible implementation implements the following interfaces, which are to be added to the core library declarations (lib.d.ts):
interface IPromiseConstructor<T> {
new (init: (resolve: (value: T | IPromise<T>) => void, reject: (reason: any) => void) => void): IPromise<T>;
}
interface IPromise<T> {
then<TResult>(onfulfilled: (value: T) => TResult | IPromise<TResult>, onrejected: (reason: any) => TResult | IPromise<TResult>): IPromise<TResult>;
}
The following libraries contain compatible Promise implementations:
- ES6 - http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-objects
- WinJS - http://msdn.microsoft.com/en-us/library/windows/apps/br211867.aspx
- Q - https://github.com/kriskowal/q
- RSVP - https://github.com/tildeio/rsvp.js/
- Bluebird - https://github.com/petkaantonov/bluebird
- es6-promise - https://github.com/jakearchibald/es6-promise
- lie - https://github.com/calvinmetcalf/lie
- when - https://github.com/cujojs/when
- asyncjs - https://github.com/rbuckton/asyncjs
A Grammar
A.1 Types
CallSignature [Await,AsyncParameter] :
TypeParameters opt ( ParameterList [?Await,?AsyncParameter]opt ) TypeAnnotation opt*
ParameterList_ [Await,AsyncParameter] *:_
RequiredParameterList [?Await]
OptionalParameterList [?Await,?AsyncParameter]
RestParameter [?Await]
RequiredParameterList [?Await] , OptionalParameterList [?Await,?AsyncParameter]
RequiredParameterList [?Await] , RestParameter [?Await]
OptionalParameterList [?Await,?AsyncParameter] , RestParameter [?Await]
RequiredParameterList [?Await] , OptionalParameterList [?Await,?AsyncParameter] , RestParameter [?Await]
RequiredParameterList [Await] :
RequiredParameter [?Await]
RequiredParameterList [?Await] , RequiredParameter [?Await]
RequiredParameter [Await] :
AccessibilityModifier opt BindingIdentifier [?Await] TypeAnnotation opt
Identifier : StringLiteral
OptionalParameterList [Await,AsyncParameter] :
OptionalParameter [?Await,?AsyncParameter]
OptionalParameterList [?Await,?AsyncParameter] , OptionalParameter [?Await,?AsyncParameter]
OptionalParameter [Await,AsyncParameter]:
[+AsyncParameter] AccessibilityModifier opt BindingIdentifier [Await] ? TypeAnnotation opt
[+AsyncParameter] AccessibilityModifier opt BindingIdentifier [Await] TypeAnnotation opt Initialiser [In]
[+AsyncParameter] BindingIdentifier [Await] ? : StringLiteral
[~AsyncParameter] AccessibilityModifier opt BindingIdentifier [?Await] ? TypeAnnotation opt
[~AsyncParameter] AccessibilityModifier opt BindingIdentifier [?Await] TypeAnnotation opt Initialiser [In,?Await]
[~AsyncParameter] BindingIdentifier [?Await] ? : StringLiteral
RestParameter [Await]:
... BindingIdentifier [?Await] TypeAnnotation opt
A.2 Expressions
BindingIdentifier [Await] : ( Modified )
Identifier but not await
[~Await] await
PropertyAssignment [Await] :
PropertyName : AssignmentExpression [?Await]
PropertyName CallSignature { FunctionBody }
GetAccessor
SetAccessor
async [no LineTerminator here] PropertyName CallSignature [Await,AsyncParameter] { FunctionBody [Await] }
GetAccessor :
get PropertyName ( ) TypeAnnotationopt { FunctionBody }
async [no LineTerminator here] get PropertyName ( ) TypeAnnotation opt { FunctionBody [Await] }
FunctionExpression [Await] : ( Modified )
function BindingIdentifier [?Await]opt CallSignature { FunctionBody }
async [no LineTerminator here] function BindingIdentifier [?Await]opt CallSignature [Await,AsyncParameter] { FunctionBody [Await] }
AssignmentExpression [Await] : ( Modified )
...
ArrowFunctionExpression [?Await]
ArrowFunctionExpression [Await] :
ArrowFormalParameters => Block [?Await]
ArrowFormalParameters => AssignmentExpression [?Await]
async [no LineTerminator here] CallSignature [Await,AsyncParameter] => Block [Await]
async [no LineTerminator here] CallSignature [Await,AsyncParameter] => AssignmentExpression [Await]
ArrowFormalParameters [Await] :
CallSignature
BindingIdentifier [?Await]
UnaryExpression [Await] : ( Modified )
...
< Type > UnaryExpression [?Await]
[+Await] await UnaryExpression [Await]
A.3 Functions
FunctionDeclaration [Await] : ( Modified )
FunctionOverloads [?Await]opt FunctionImplementation [?Await]
FunctionOverloads [Await] :
FunctionOverloads [?Await]opt FunctionOverload [?Await]
FunctionOverload [Await] :
function BindingIdentifier [?Await] CallSignature ;
FunctionImplementation [Await] :
function BindingIdentifier [?Await] CallSignature { FunctionBody }
async [no LineTerminator here] function BindingIdentifier [?Await] CallSignature [Await,AsyncParameter] { FunctionBody [Await] }
A.4 Classes
MemberFunctionImplementation:
AccessibilityModifieropt static opt PropertyName CallSignature { FunctionBody }
AccessibilityModifieropt static opt async [no LineTerminator here] PropertyName CallSignature [Await,AsyncParameter] { FunctionBody [Await] }
B Helper Functions
There are two helper functions that are used for Async Functions. The __awaiter helper function is used by both the ES6 as well as the ES5/ES3 transformations. The __generator helper function is used only by the ES5/ES3 transformation.
B.1 __awaiter helper function
var __awaiter = __awaiter || function (g) {
function n(r, t) {
while (true) {
if (r.done) return r.value;
if (r.value && typeof (t = r.value.then) === "function")
return t.call(r.value, function (v) { return n(g.next(v)) }, function (v) { return n(g["throw"](v)) });
r = g.next(r.value);
}
}
return n(g.next());
};
B.2 __generator helper function
var __generator = __generator || function (m) {
var d, i = [], f, g, s = { label: 0 }, y, b;
function n(c) {
if (f) throw new TypeError("Generator is already executing.");
switch (d && c[0]) {
case 0 /*next*/: return { value: void 0, done: true };
case 1 /*throw*/: throw c[1];
case 2 /*return*/: return { value: c[1], done: true };
}
while (true) {
f = false;
switch (!(g = s.trys && s.trys.length && s.trys[s.trys.length - 1]) && c[0]) {
case 1 /*throw*/: i.length = 0; d = true; throw c[1];
case 2 /*return*/: i.length = 0; d = true; return { value: c[1], done: true };
}
try {
if (y) {
f = true;
if (typeof (b = y[c[0]]) === "function") {
b = b.call(y, c[1]);
if (!b.done) return b;
c[0] = 0 /*next*/, c[1] = b.value;
}
y = undefined;
f = false;
}
switch (c[0]) {
case 0 /*next*/: s.sent = c[1]; break;
case 3 /*yield*/: s.label++; return { value: c[1], done: false };
case 4 /*yield**/: s.label++; y = c[1]; c[0] = 0 /*next*/; c[1] = void 0; continue;
case 6 /*endfinally*/: c = i.pop(); continue;
default:
if (c[0] === 1 /*throw*/ && s.label < g[1]) { s.error = c[1]; s.label = g[1]; break; }
if (c[0] === 5 /*break*/ && (!g || (c[1] >= g[0] && c[1] < g[3]))) { s.label = c[1]; break; }
s.trys.pop();
if (g[2]) { i.push(c); s.label = g[2]; break; }
continue;
}
f = true;
c = m(s);
} catch (e) {
y = void 0;
c[0] = 1 /*throw*/, c[1] = e;
}
}
}
return {
next: function (v) { return n([0 /*next*/, v]); },
1 /*throw*/: function (v) { return n([1 /*throw*/, v]); },
2 /*return*/: function (v) { return n([2 /*return*/, v]); },
};
};
B.2.1 _generator Arguments
| argument | description |
|---|---|
m |
State machine function. |
B.2.2 n Arguments
| argument | description |
|---|---|
c |
The current instruction. |
B.2.3 Variables
| variable | description |
|---|---|
d |
A value indicating whether the generator is done executing. |
i |
A stack of instructions (see below) pending execution. |
f |
A value indicating whether the generator is executing, to prevent reentry (per ES6 spec). |
g |
The region at the top of the s.trys stack. |
s |
State information for the state machine function. |
s.label |
The label for the next instruction. |
s.trys |
An optional stack of protected regions for try..catch..finally blocks. |
s.sent |
A value sent to the generator when calling next. |
s.error |
An error caught by a catch clause. |
y |
The current inner generator to which to delegate generator instructions. |
b |
The method on n to execute for the current instruction. One of "next", "throw", or "return". |
B.2.4 Instructions
| instruction | args | description |
|---|---|---|
0 /*next*/ |
0-1 | Begin or resume processing with an optional sent value. |
1 /*throw*/ |
1 | Throw an exception at the current instruction. Executes any enclosing catch or finally blocks. |
2 /*return*/ |
0-1 | Returns a value from the current instruction. Executes any enclosing finally blocks. |
3 /*yield*/ |
0-1 | Suspends execution and yields an optional value to the caller of the generator. |
4 /*yield**/ |
1 | Delegates generator operations to the provided iterable (not needed for Async Functions, but provided for future support for down-level Generator Functions). |
5 /*break*/ |
1 | Jumps to a labeled instruction. Executes any enclosing finally blocks if the target is outside of the current protected region. |
6 /*endfinally*/ |
0 | Marks the end of a finally block so that the previous break, throw, or return instruction can be processed. |
B.2.5 Protected Regions
A protected region marks the beginning and end of a try..catch or try..finally block. Protected regions are pushed onto the s.trys stack whenever a protected region is entered when executing the state machine. A protected region is defined using a quadruple in the following format:
| field | required | description |
|---|---|---|
| 0 | yes | The start of a try block. |
| 1 | no | The start of a catch block. |
| 2 | no | The start of a finally block. |
| 3 | yes | The end of a try..catch..finally block. |
B.3 __generator helper function (alternate)
var __generator = __generator || function (body) {
var done, instructions = [], stepping, region, state = { label: 0 }, delegated;
function step(instruction) {
if (stepping) throw new TypeError("Generator is already executing.");
if (done) {
switch (instruction[0]) {
case 0 /*next*/: return { value: void 0, done: true };
case 1 /*throw*/: throw instruction[1];
case 2 /*return*/: return { value: instruction[1], done: true };
}
}
while (true) {
stepping = false;
var region = state.trys && state.trys.length && state.trys[state.trys.length - 1];
if (region) {
switch (instruction[0]) {
case 1 /*throw*/:
instructions.length = 0;
done = true;
throw instruction[1];
case 2 /*return*/:
instructions.length = 0;
done = true;
return { value: instruction[1], done: true };
}
}
try {
if (delegated) {
stepping = true;
var callback = delegated[instruction[0]];
if (typeof callback === "function") {
var result = callback.call(delegated, instruction[1]);
if (!result.done) return result;
instruction[0] = 0 /*next*/;
instruction[1] = result.value;
}
delegated = undefined;
stepping = false;
}
switch (instruction[0]) {
case 3 /*yield*/:
state.label++;
return { value: instruction[1], done: false };
case 4 /*yield**/:
state.label++;
delegated = instruction[1];
instruction[0] = 0 /*next*/;
instruction[1] = void 0;
continue;
case 0 /*next*/:
state.sent = instruction[1];
break;
case 6 /*endfinally*/:
instruction = instructions.pop();
continue;
default:
if (instruction[0] === 5 /*break*/ && (!region || (instruction[1] >= region[0] && instruction[1] < region[3]))) {
state.label = instruction[1];
break;
}
if (instruction[0] === 1 /*throw*/ && state.label < region[1]) {
state.error = instruction[1];
state.label = region[1];
break;
}
state.trys.pop();
if (region[2]) {
instructions.push(instruction);
state.label = region[2];
break;
}
continue;
}
stepping = true;
instruction = body(state);
} catch (e) {
delegated = void 0;
instruction[0] = 1 /*throw*/, instruction[1] = e;
}
}
}
return {
next: function (v) { return step([0 /*next*/, v]); },
"throw": function (v) { return step([1 /*throw*/, v]); },
"return": function (v) { return step([2 /*return*/, v]); },
};
};
If memory serves the CoffeeScript guys refused to take a PR that covered similar ground. The result was a fork of the project called Iced CoffeeScript: http://maxtaco.github.io/coffee-script/
I'm not sure if es5 / es3 support is worth the trouble because of the debugging story. I value the TS being not too different from the JS. It wouldn't be in this case and so even if available it would probably be a feature I chose not to use with es3 / es5
For es3 & 5, it might be cleaner to use a callback based emit instead of a state machine? I think an emit like this would be a lot cleaner & more readable:
// TypeScript
var p0: Promise<number> = /* ... */;
var p1: Promise<number> = /* ... */;
async function fn() {
var i = await p0;
return await p1 + i;
}
// JavaScript
function fn() {
var i;
return Promise.resolve(void 0).then(_a);
function _a() {
return p0.then(_b);
}
function _b(value) {
i = value;
p1.then(_c);
}
function _c(value) {
return value + i;
}
}
// TypeScript
var p0: Promise<number> = /* ... */;
var p1: Promise<number> = /* ... */;
async function fn() {
try {
await p0;
}
catch (e) {
if (foo) return 42;
if (bar) return await p1;
alert(e.message);
if (baz) {
await p1;
}
}
finally {
await p1;
}
}
// JavaScript
function __asyncTryCatch(_try, _catch, _finally) {
Promise.resolve(void 0).then(_try).then(_finally, function(err) {
return Promise.resolve(_catch(err)).then(function(value) { // value: [boolean, T | Promise<T>]
if (value[0]) { // return
return value[1]; // Can be Promise<T> or T.
} else {
// value[1] can be Promise<T> or T, so we need te convert it to Promise<T>
return Promise.resolve(value[1]).then(_finally);
}
}, function(err) {
Promise.resolve(_finally()).then(function() {
throw err;
});
});
});
}
function fn() {
return Promise.resolve(void 0).then(_a);
function _a() {
return __asyncTryCatch(_b, _c, _d).then(_e);
}
function _b() {
return p0;
}
function _c(e) {
if (foo) return [true, 42];
if (bar) return [true, p2];
alert(e.message);
if (baz) {
return [false, p1];
}
return [false, void 0];
}
function _d() {
return p1;
}
function _e() {
return void 0;
}
}
// TypeScript
async function fn() {
var data = await bar(1);
if (data.foo) {
console.log(await bar(2));
console.log(await bar(3));
}
for (var i = 0; i < 10; i++) {
await bar(4);
}
return data;
}
// JavaScript
function fn() {
var data, i, dataObj;
return Promise.resolve(void 0).then(_a); // Start in a Promise context, since a Promise catches errors
function _a() {
return bar(1).then(_b);
}
function _b(value) {
data = value;
if (data.foo) {
return bar(2).then(_c);
}
return _e();
}
function _c(value) {
console.log(value);
return bar(3).then(_d);
}
function _d(value) {
console.log(value);
return _e();
}
function _e() { // Code after the 'if' is wrapped in a function, otherwise it would be emitted twice.
i = 0;
return _f();
}
function _f() {
if (i < 10) {
return bar(4).then(_g);
}
return data;
}
function _g() {
i++;
return _f();
}
}
A function will be cut in smaller functions. This way there are no nested callback needed.
Advantages:
- Promises already handle errors (you can throw errors in a then callback).
- You can easily control the order of execution (with
for,ifet cetera) with thethenmethods. - No need for big helper functions (only __asyncTryCatch)
@ivogabe
The original proposal is for emitting generators in general, not just async-await, so it can't rely on Promises. Generators are synchronous whereas a Promise never resolves synchronously.
Also, your alternative emit is equivalent to the proposed state machine:
- The proposed state machine has a case-block for each states, while yours has a closure for each state.
- A state in the proposed state machine would return a label for the next state, while yours does a .then() with the next function as the parameter.
- The proposed state machine is driven by a driver that interprets the state transitions, while yours relies on Promise.then() for that.
If it's a matter of readability, you could apply the same transformation for the generator state machine. Just move each case-block to its own closure, and make each closure return a reference to the next closure to call instead of the label of the next state (i.e., instead of return ["break", 6]; do return _g;). The switch-case based state machine is just the canonical implementation (it's also smaller than wrapping each state into its own closure and, more importantly, doesn't blow the stack for long loops since it's effectively TCO'd). There is no difference in complexity between the two emits (neither for the compiler that needs to emit it, nor for the human that needs to read it) - they both require the same rewrite.
I would add to @Arnavion's comment, that if you desugar async functions to something other than generators, the ES6 output will be a significant transformation. One of the nice things about the current proposal is that the ES6 emit for async functions is quite simple.
@arnavion While you could rewrite this way, it would make handling try..catch..finally much more complex. By using labels, I am able to define a protected region, such that any abrupt completion or break instruction properly executes any containing finally clauses.
I will update the proposal shortly with a tentative version of __generator that is more verbose, for further discussion.
The version of __generator in B.2 is 2,233 bytes unminified, 1,034 bytes minified.
The version of __generator in B.3 is 3,831 bytes unminified, 1,059 bytes minified.
Minified sizes are from UglifyJS.
@JsonFreeman I think @ivogabe is only talking about that alternative emit for ES3 and ES5 emit. The ES6 emit would still use yield and __awaiter.
@rbuckton The ES3/5 emit for generators is somewhat a separate issue from the TS support for ES7 async and its ES6 emit. Could you split it into a separate proposal?
I didn't see it here, but is there a proposal for syntax to have parallel awaits?
Something like:
var [i, j] = await [x,y];
@eggers Not at the moment, but you can achieve this with something like:
var [i, j] = await Promise.all([x, y]);
There's also await*
@Arnavion await* Isn't specified, though it could be used for that purpose. ~~See https://github.com/lukehoban/ecmascript-asyncawait#await-and-parallelism for more information.~~
Supporting await* would limit the ability to support Promise implementations from other libraries, unless they also support the Promise.all method.
Edit: Just noticed your comment included the same link.
@JsonFreeman I only meant to emit such code for ES3 and ES5. ES6 supports generators natively, so it's a good thing to use that there. But in my opinion it's a bit strange to "use" generators on older versions by emitting downlevel generators. Since we already need to think of a downlevel emit, I'd rather use Promise#then linking.
Also I think using Promise#then would be closer to the kind of code a human would write, and one of the design goals is to emit clean, idiomatic, recognizable JavaScript code. For generators in general that might be hard, but for async functions it can be done using Promises.
@ivogabe @JsonFreeman While I agree that this makes some sense, the problem is that many control flow mechanisms, especially iteration, do not compose well with continuations and require authoring more and more complex closures to properly handle state. The same can be said for using await inside of an expression with side-effects (e.g. shortcutting in a logical binary expression, etc.). Using callbacks to keep the emit clean and recognizable falls apart for anything moderately complex.
As a user I'd vote in favour of splitting into two milestones. First milestone: outputting ES6, and maybe adding an explicit feature to the VS TypeScript project tab to call my choice of transpiler (6to5, traceur) for every .ts in my project.
This would surely be the fastest way to get async coding style into the hands of your users. Debugging experience would not be perfect, but it would be better than nothing.
Second milestone: fix the debugging experience by integrating generation to get end-to-end source maps.
Good work guys!
I don't think @Arnavion's proposal of pointing users to some alternate framework for ES3/ES5 async/await support makes sense. Most people are not going to be willing (or able?) to chain together multiple products to add support for this feature, and the debugging experience for such a scenario will almost certainly be significantly worse than if the compiler does the re-writing itself.
Then there's the argument that if there's a bug in the emitted code you'll have to wait for the TS team to fix it in the next version. How is this different from any other compiler feature that users rely on? The only difference is the code is being emitted rather than being restricted to being in the black box. I've been using TS since v0.8, I can assure you there has been no lack for user-impacting compiler bugs.
It'll likely be years before the overwhelming majority of users are on ES6 browsers- that seems like a long time to wait to be able to use this feature on the web. This makes ES3/ES5 support all the more important. I'd also say MS should be in a good position to judge the testing and debugging work here as they've added async/await to two separate C# compilers in the past 5 years.
I couldn't tell for certain, but is this proposal limited to allowing only Promises to participate in async/await and not generator functions, once they become available?
I'll stop arguing this point, because users who want to use other transpilers have the option to emit in ES6 mode and do just that. So let me just answer these few last points:
Most people are not going to be willing (or able?) to chain together multiple products to add support for this feature
It is trivial for users that have a build system. Such users already chain together multiple products (even if it's just compiler + minifier), or can trivially do so, so adding one more is a tiny change.
It is likely only a problem for VS users that rely on compilation from msbuild to do everything, and don't even want to add post-build events for such post-processing.
and the debugging experience for such a scenario will almost certainly be significantly worse than if the compiler does the re-writing itself.
Regenerator (like any competent rewriter) supports input sourcemaps.
How is this different from any other compiler feature that users rely on?
I already answered this question. The scope of possible bugs and the ability to work around them is different.
This makes ES3/ES5 support all the more important.
Of course. That is why we already have transpilers without TS needing to make itself a new one.
It is likely only a problem for VS users that rely on compilation from msbuild to do everything, and don't even want to add post-build events for such post-processing.
TS comes bundled with Visual Studio. I don't have any data to support this but my assumption would be that most TS users are Visual Studio users. It seems odd to want to discount this user base.
It's certainly possible to add a bunch of post-processing steps, and not all that difficult, but every build step you add is another possible source of errors, and from my personal experience the majority of developers use what you give them out of the box and don't go wiring up their own plumbing.
How is this different from any other compiler feature that users rely on?
I already answered this question. The scope of possible bugs and the ability to work around them is different.
So say TS 1.5 comes out and for some reason extends no longer works. As in, adding an extends clause doesn't change the emit at all from just a plain class declaration. Now, everything in your code is broken, and the only way to fix it (besides the TS team patching the bug) is to rewrite your code to manually create the inheritance code TS had been emitting for you. You are likely forced to change the semantics of your code in order to accomplish this. This is the same story for any compiler feature.
The fact that you currently could override a problem with the emitted __extends is more of an happy accident than a design feature.
Of course. That is why we already have transpilers without TS needing to make itself a new one.
TS is, always has been, and always will be a transpiler. Even in ES6 mode, TS will still have features that transpile (like enums). And there are current proposals for even more transpilation features (annotations).
I don't have any data to support this
Exactly.
It might be news to you that the TS compiler is available on npm, and the TS experience is supported by many more IDEs and text editors than just VS.
It seems odd to want to discount this user base.
Then it's a good thing I didn't do that, since I suggested what all user bases could do.
and from my personal experience the majority of developers use what you give them out of the box
Post-build events are part of the msbuild project file.
So say TS 1.5 comes out and for some reason extends no longer works. ... Now, everything in your code is broken, and the only way to fix it
... is to go back to 1.4 and wait for 1.5.1. But let's play along and assume you don't want to do that:
is to rewrite your code to manually create the inheritance code TS had been emitting for you.
Said "rewrite" consists of adding a single utility function and one single call to that utility function per class. The class's emit itself remains unchanged and unaffected.
You are likely forced to change the semantics of your code in order to accomplish this.
False. Since __extends is not such a large rewrite like the state-machine rewrite, it is trivial to bolt on.
The fact that you currently could override a problem with the emitted __extends is more of an happy accident than a design feature.
No, it is absolutely a design feature.
TS is, always has been, and always will be a transpiler.
It was a transpiler until it didn't have an ES6 emit mode. Now it needn't be. And again, transpiling class Foo extends Bar to __extends(Foo, Bar); is on a different scale than the rewrite for generators.
Even in ES6 mode, TS will still have features that transpile (like enums).
We're only talking about transpiling ES features here. The fact that it transpiles non-ES features to JS is irrelevant.