CodeBlanks Logo Icon CodeBlanks

Summary - async/await

Combine async/await and Promise.all to write a file processor.

Summary - async/await

In this group you learned the async/await syntax. async functions always return a Promise; await lets you wait for a Promise's result in a synchronous-looking way. You catch errors with try/catch.

For parallel work you use await Promise.all([...]); for sequential dependent work you write consecutive await calls. Choosing the right approach shapes both readability and speed. async/await offers a flatter flow than then chains.

Practice Your turn: get a value with await

Define async function run(). Write const v = await Promise.resolve("done"). Log it with console.log(v). Call run().

Starter code

index.js
// Define async function run
// Get the value with await Promise.resolve, log with console.log
// Finally call run

Sample solution

index.js
async function run() {
  const v = await Promise.resolve("done");
  console.log(v);
}
run();

Expected output

done

Practice Your turn: try/catch with await

Define async function run(). Inside a try block, write const v = await Promise.reject(new Error("error")). Inside catch (err), write console.log(err.message). Call run().

Starter code

index.js
// Define async function run
// try: await Promise.reject; catch: console.log(err.message)
// Finally call run

Sample solution

index.js
async function run() {
  try {
    const v = await Promise.reject(new Error("error"));
  } catch (err) {
    console.log(err.message);
  }
}
run();

Expected output

error

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 async/await parts

Term Meaning
async returns a Promise
await waits for result
try/catch catches errors

2 What does a returned value become in an async function?

  • It throws an error
  • It is returned as is
  • It becomes undefined
  • It is wrapped in a Promise Correct answer

Explanation: An async function's return value is wrapped in a Promise.

All lessons in Beginner