TypeScriptLesson 15 of 16

async/await and typed Promises

Promise<T> is a promise to deliver a value of type T a little later. await unwraps that value, and TypeScript knows its type.

Key points

  • An async function always returns a Promise: async function load(): Promise<string>.
  • await fetchUser(1) has the type User, not Promise<User>.
  • Promise.all waits for several promises and keeps their types: [User, User].
  • In catch the error is unknown, so check it with instanceof Error.

Example

interface User {  id: number;  name: string;} // A stand-in for a real API call: it answers with a ready Promisefunction fetchUser(id: number): Promise<User> {  return Promise.resolve({ id, name: id === 1 ? "Ada" : "Linus" });} async function greet(id: number): Promise<string> {  const user = await fetchUser(id); // user: User  return `Hi, ${user.name}`;} async function main(): Promise<void> {  console.log(await greet(1));  const [a, b] = await Promise.all([fetchUser(1), fetchUser(2)]); // [User, User]  console.log(`${a.name} & ${b.name}`);} main();

fetchUser stands in for a real server request, so the result is always the same. Promise.all returned a tuple, and a.name and b.name are already strings.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Make getPrice reject unknown items with an error, turn total into an async function that adds prices via Promise.all, and let main print "Order 1: 11" and "Order 2 failed: No price for pizza".

Output

What your program prints appears here.