0

I am playing around with promises and the Fetch API in Javascript

I wanted to know why when I do not add an implicit return in my countryDetail() function, I get undefined, whereas when I add an implicit return I get the data I am looking for?

Here is the function without the implicit return which returns undefined.

const countryDetail = (countryCode) => {
  return fetch("http://restcountries.eu/rest/v2/all")
    .then((response) => {
      if (response.status === 200) {
        return response.json();
      } else {
        throw new Error("Unable to fetch data");
      }
    })
    .then((data) => data.find((country) => country.alpha2Code === countryCode);
};

Here is the same function with the implicit return using the arrow function. This function works and return the data instead of undefined

const countryDetail = (countryCode) => {
  return fetch("http://restcountries.eu/rest/v2/all")
    .then((response) => {
      if (response.status === 200) {
        return response.json();
      } else {
        throw new Error("Unable to fetch data");
      }
    })
    .then((data) => {
      return data.find((country) => country.alpha2Code === countryCode);
    });

here is how the function is being used in app.js

countryDetail("MX")
  .then((country) => {
    console.log(country.name);
  })
  .catch((err) => {
    console.log(err);
  });
user6248190
  • 1,233
  • 2
  • 16
  • 31
  • Maybe it is me, but I can't see the function with the implicit return. I only see the one without implicit return and how it is used in app.js – urchmaney Jan 01 '21 at 11:32
  • @urchmaney sorry the question has been updated now – user6248190 Jan 01 '21 at 11:33
  • Other than couple of missing parenthesis, your code is fine. Both code examples work as they should. Only different between the two versions of `countryDetail` function is that first one returns the data implicitly and second one returns the data explicitly. – Yousaf Jan 01 '21 at 11:33
  • Does this answer your question? [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) – Aluan Haddad Jan 01 '21 at 11:38
  • @AluanHaddad no, it looks like it was a syntax issue, I added the missing parenthesis and it worked. – user6248190 Jan 01 '21 at 11:42
  • I see what you're saying. It's too bad this code even parses – Aluan Haddad Jan 01 '21 at 11:44
  • yeah it's weird, now I need to figure out why this code even parsed and didn't raise an error – user6248190 Jan 01 '21 at 11:47

1 Answers1

3

It seems, there is a syntactical error in the implicit code. Closing bracket is missing.

.then((data) => data.find((country) => country.alpha2Code === countryCode);

It should be

.then((data) => data.find((country) => country.alpha2Code === countryCode));
tsfahmad
  • 404
  • 4
  • 12