Downlevel Async Functions
This feature was supported before TypeScript 2.1, but only when targeting ES6/ES2015.TypeScript 2.1 brings the capability to ES3 and ES5 run-times, meaning you’ll be free to take advantage of it no matter what environment you’re using.
Note: first, we need to make sure our run-time has an ECMAScript-compliant
Promise
available globally.That might involve grabbing a polyfill forPromise
, or relying on one that you might have in the run-time that you’re targeting.We also need to make sure that TypeScript knowsPromise
exists by setting yourlib
flag to something like"dom", "es2015"
or"dom", "es2015.promise", "es5"
Example
tsconfig.json
{
"compilerOptions": {
"lib": ["dom", "es2015.promise", "es5"]
}
}
dramaticWelcome.ts
function delay(milliseconds: number) {
return new Promise<void>(resolve => {
setTimeout(resolve, milliseconds);
});
}
async function dramaticWelcome() {
console.log("Hello");
for (let i = 0; i < 3; i++) {
await delay(500);
console.log(".");
}
console.log("World!");
}
dramaticWelcome();
Compiling and running the output should result in the correct behavior on an ES3/ES5 engine.