2

I am trying to get user data from github using an url, I am new to dealing with APIs. I tried to follow github-api, but the code there makes little sense to me. I understand the concept of promises, so I tried to couple up this stackoverflow answer with promises and tried to implement it as below. I am working with node.

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

var request = new XMLHttpRequest();

function pr() {
  return new Promise(function(resolve, reject) {
    request.open('get', 'https://api.github.com/users/$username')
    request.send();
    resolve(request.response);
  });
}

var gitpr = pr();
gitpr.then(function() {
  console.log(request.response);
})

My request.response [[PromiseValue]] is undefined on running the code in node.

Whereas the result in console is correct if I follow this stackoverflow answer(same as above).

HarshvardhanSharma
  • 754
  • 2
  • 14
  • 28
  • 1
    you didn't define an "onload" event handler function for your XMLHttpRequest...you're not waiting for the request to complete before you resolve the Promise – ADyson Nov 10 '18 at 22:45

1 Answers1

2

You are not doing anything to wait for the request to return!

XMLHttpRequest will notify you when the request is complete with onreadystatechange

Below is a pr() function that accomplishes your objectives, assuming "$username" is something meaningful.

Note: I have put the request object into the function for better encapsulation, and am communicating the value of the response to the caller via the resolve:

function pr() {
  var request = new XMLHttpRequest();
  return new Promise(function(resolve, reject) {
    request.onreadystatechange = function() {
      if (request.readyState == 4) {
        resolve(request.responseText);
      }
    }
    request.open('get', 'https://api.github.com/users/$username', true)
    request.send();
  });
}

resolve then sends the responseText member of the response to the function that is awaiting the Promise in the value of it's first function:

pr().then(function(val) {
  console.log(val)
}, function(err) {
  console.log(err)
}) 

In the pr() function we are not calling reject() so that err function can't be called, but it would be a good idea to, for example, check for an error status code and call reject on that.

Blunt Jackson
  • 616
  • 4
  • 17
  • Why do I need **Promise** if the call is asynchronous (via xmlhttprequest) and therefore is like a Promise in itself. Is Promise here double, so too much? – Timo Dec 06 '20 at 12:08