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 withnew Error("Failed to fetch data.")whensuccessis false.getData(success)awaitsfetchData(success)insidetry/catch. It returns the value, or the error'smessagewhen it fails, so the grader can read what aconsole.logwould 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(...).