In TypeScript, one can wrap a promise with async/await syntax to make the code cleaner and more readable. Here is an example:
index.ts132 chars6 lines
In the above example, fetchData
function is marked with async
keyword which allows us to use await
inside the function. The await
keyword can be used to wait for a promise to resolve or reject. The fetch
function returns a promise that resolves to a Response
object. We use await
to wait for this promise to resolve and get the Response
object. Then, we use the json()
method on the Response
object which also returns a promise, so we use await
again to wait for this promise to resolve and get the data. Finally, we return the data.
Note that when using async/await, the function returns a Promise
. So, in the example above, fetchData
would return a Promise<any>
because we don't know exactly what the data would be. You could replace any
with a more specific type to avoid compiler warnings.
Hope this helps!
gistlibby LogSnag