call(back)

Create and Consume a Promise

Write a function that returns a promise, and code that uses it.

  • fetchData(success = true) returns a promise that settles 1,000 ms after the call. It resolves with "Data fetched successfully!", or rejects with new Error("Failed to fetch data.") when success is false.
  • getData(success) awaits fetchData(success) inside try/catch. It returns the value, or the error's message when it fails, so the grader can read what a console.log would have printed.

Everything runs on a virtual clock, so the grader sees exactly when each promise settles.

Hints

Hint 1

fetchData is a new Promise whose executor starts a 1,000 ms setTimeout and calls resolve or reject inside it. Reject with an Error, not a string, so callers get a stack and a message.

Hint 2

getData is try { return await fetchData(success); } catch (err) { return err.message; } — the same consumption as .then(...).catch(...).

Asked at