Search code examples
javascriptes6-promiseaddeventlistener

I'm exploring JavaScript Promises with event handlers


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.


Solution

  • 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);
        }
      )}
    );