0

I have a function that returns a promise:

const getCountry = countryCode =>
  new Promise((resolve, reject) => {
    const countryRequest = new XMLHttpRequest();

    countryRequest.addEventListener('readystatechange', e => {
      if (e.target.readyState === 4 && e.target.status === 200) {
        const data = JSON.parse(e.target.responseText);
        const country = data.find(
          country => country.alpha2Code === countryCode
        );
        resolve(country);
      } else if (e.target.readyState === 4) {
        reject('Unable to fetch data');
      }
    });

    countryRequest.open('GET', 'http://restcountries.eu/rest/v2/all');
    countryRequest.send();
  });

This works fine. The problem is in this next snippet.

const btn = document.getElementById('clickme');

btn.addEventListener(
  'click',
  getCountry('US').then(
    country => {
      console.log('this is from the resolve');
    },
    err => {
      console.log(err);
    }
  )
);

My problem is that I'm getting this is from the resolve printing to the console before I click the button to fire the event and I don't know why. I'm wanting this to wait until I click the button before it prints to the console because I have to create a table out of the data that comes back AFTER the button is clicked. Thanks for all the help.

MMelvin0581
  • 509
  • 6
  • 20
  • 1
    Should be `() => getCountry('US').then( ...` You're calling the function instead of passing a function to the event handler. – JJJ Jun 02 '18 at 05:11
  • Possible duplicate of [onclick event fires before button clicked - javascript](https://stackoverflow.com/questions/17351853/onclick-event-fires-before-button-clicked-javascript) – JJJ Jun 02 '18 at 05:12
  • Yes I figured it out as soon as I posted on stack of course... – MMelvin0581 Jun 02 '18 at 05:13

2 Answers2

1

That is happening because you are declaring a function there istead of passing a reference inside addEventListener you can do this instead :

btn.addEventListener(
  'click',
 ()=> { getCountry('US').then(
    country => {
      console.log('this is from the resolve');
    },
    err => {
      console.log(err);
    }
  )}
);
supra28
  • 1,646
  • 10
  • 17
0

I figured it out guys, sorry for the post.

btn.addEventListener(
  'click', () =>
  getCountry('US').then(
    country => {
      console.log('this is from the resolve');
    },
    err => {
      console.log(err);
    }
  )
);

I was missing an arrow...

MMelvin0581
  • 509
  • 6
  • 20