TypeScript theorytheory 0/50 · 0%
Async · medium

29. Async/await and Promise<T>

Typed asynchronous code without callback nesting.

An `async` function always returns a `Promise`, and its declared return type is wrapped automatically: writing `Promise<number>` as the return type means `await`ing the call yields `number`.

ts
async function fetchBalance(address: string): Promise<number> {
  const response = await fakeRpcCall(address);
  return response.balance;
}

async function main() {
  const balance = await fetchBalance("0xabc");
  console.log(balance.toFixed(2)); // balance is number, not Promise<number>
}

`Promise.all` types an array/tuple of promises into a tuple of their resolved values: `Promise.all([p1, p2])` where `p1: Promise<A>` and `p2: Promise<B>` resolves to `[A, B]`. Errors from a rejected promise should be handled with `try/catch` around `await`, or `.catch()` on the promise chain.

Check your understanding

  1. 1. What does an `async function` always return?

  2. 2. After `const balance = await fetchBalance(...)` where the function returns `Promise<number>`, what type is `balance`?

  3. 3. What does `Promise.all([p1, p2])` resolve to if `p1: Promise<A>` and `p2: Promise<B>`?