logo
logo

Star Wars Planets

Beginner

Star Wars Planets

Fetch the names of the first 5 planets using Promises.

The
getPlanets
function fetches a list of planets from the Star Wars API and returns an array containing the names of the first 5 planets. Rewrite the function to use Promises instead of
async/await
.

Signature

getPlanets(): Promise<string[]>

Instructions:

  1. Use the
    fetch
    function to make a GET request to the Star Wars API endpoint:
    https://swapi.dev/api/planets/
    .
  2. Parse the response JSON using the Promise-based
    json()
    method.
  3. Extract the names of the first 5 planets from the
    results
    array of the response data, and return them as an array of strings.
  4. If any errors occur during the request or response parsing, throw an error with a descriptive message.

Example:

getPlanets()
  .then(names => console.log(names))
  .catch(error => console.error(error));
// Output: ["Tatooine", "Alderaan", "Yavin IV", "Hoth", "Dagobah"]

Console
Submit
Solution
00:00