DAB DAB - 1 month ago 15
Javascript Question

return new Promise() not working in Node.js

I'm new to the concept of promises, as well as to JavaScript in general. I'm trying to write a function in Node.js that I can pass a URL to a promise of the results.

I have programmed it two ways. The first does not work, in which I can pass the URL to the function. The second does work, in which the URL is statically defined. The first one does not work because the compiler does not think it is a function for some reason that I can't figure out, why?

THIS WAY DOESN'T WORK as the function

getJson
is not interpreted by Node as a function:

var options = { method: 'GET',
url: URL, // This will be dynamically filled by the argument to the function getJson
headers: { authorization: 'OAuth realTokenWouldBeHere', Accept: 'application/json' } };

var getJson = function(URL){

return new Promise(function(resolve, reject) {

request(options, function (error, response, body) {
if(error) reject(error);
else {
resolve(JSON.parse(body)); //The body has an array in the jason called Items
}
});
}); // Edited original post. Had two curly braces }}; here by accident, which was why function was not being recognized
};

getJson.then(function(result) {
console.log(result.Items); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});


THIS WAY DOES WORK AND I GET BACK AN ARRAY OF ITEMS TO THE CONSOLE. The downside of this is that the URL used is static. The point of what I am trying to do is to chain a bunch of URL's by taking the result of an API, one URL call that then contains he URL of the NextPage of results.

var options = { method: 'GET',
url: 'http://staticURL',
headers: { authorization: 'OAuth realTokenWouldBeHere', Accept: 'application/json' } };

var getJson = new Promise(function(resolve, reject) {
request(options, function(err, response, body) {
if(err) reject(err);
else {
resolve(JSON.parse(body));
}
});
});

getJson.then(function(result) {
console.log(result.Items); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});

Answer

Try this:

var getJson = function(URL){
  var options = { 
    method: 'GET',
    url: URL,
    headers: { authorization: 'OAuth realTokenWouldBeHere', Accept: 'application/json' } 
  };
  return new Promise(function(resolve, reject) {

    request(options, function (error, response, body) {
      if(error) reject(error);
      else {
        resolve(JSON.parse(body));
      }
    });
  }};
};  

And then you can call it:

getJson(theDynamicURLGoesHere).then(function(result) {
  console.log(result.Items); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});