You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
where the `wrapToReturnPromise` just executes the generator function to get the `generator` and then use `generator.next()`, if the value is a `promise` it would `then`+`catch` the promise and depending upon the result call `generator.next(result)` or `generator.throw(error)`. That's it!
47
47
48
+
49
+
50
+
### Async Await Support in TypeScript
51
+
**Async - Await** has been supported by [TypeScript since version 1.7](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-1-7.html). Asynchronous functions are prefixed with the *async* keyword; *await* suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the *Promise* returned.
52
+
It was only supported for **target es6** transpiling directly to **ES6 generators**.
53
+
54
+
**TypeScript 2.1**[added the capability to ES3 and ES5 run-times](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html), meaning you’ll be free to take advantage of it no matter what environment you’re using. It's important to notice that we can use async / await with TypeScript 2.1 and many browsers are supported, of course, having globally added a **polyfill for Promise**.
55
+
56
+
Let's see this **example** and take a look to this code to figure out TypeScript async / await **notation** works:
57
+
```ts
58
+
function delay(milliseconds:number, count:number):Promise<number> {
59
+
returnnewPromise<number>(resolve=> {
60
+
setTimeout(() => {
61
+
resolve(count);
62
+
}, milliseconds);
63
+
});
64
+
}
65
+
66
+
// async function allways return a Promise
67
+
asyncfunction dramaticWelcome():Promise<void> {
68
+
console.log("Hello");
69
+
70
+
for (let i =0; i<5; i++) {
71
+
// await is converting Promise<number> into number
72
+
const count:number=awaitdelay(500, i);
73
+
console.log(count);
74
+
}
75
+
76
+
console.log("World!");
77
+
}
78
+
79
+
dramaticWelcome();
80
+
```
81
+
82
+
**Transpiling to ES6 (--target es6)**
83
+
```js
84
+
var __awaiter = (this&&this.__awaiter) ||function (thisArg, _arguments, P, generator) {
You can see full example [here][asyncawaites5code].
190
+
191
+
192
+
**Note**: for both target scenarios, we need to make sure our run-time has an ECMAScript-compliant Promise available globally. That might involve grabbing a polyfill for Promise. We also need to make sure that TypeScript knows Promise exists by setting your lib flag to something like "dom", "es2015" or "dom", "es2015.promise", "es5".
193
+
**We can see what browsers DO have Promise support (native and polyfilled) [here](https://kangax.github.io/compat-table/es6/#test-Promise).**
0 commit comments