返回新的Promise()在Node.js中不起作用

DAB*_*DAB 1 javascript node.js promise

我是Promise概念以及JavaScript的新手。我正在尝试在Node.js中编写一个函数,该函数可以将URL传递给结果承诺。

我用两种方法编程。第一个不起作用,我可以在其中将URL传递给函数。第二个方法确实起作用,其中URL是静态定义的。第一个不起作用,因为由于某种原因我不知道为什么编译器不认为它是一个函数,为什么?

这种方法getJson不起作用,因为Node并未将其解释为函数:

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"
});
Run Code Online (Sandbox Code Playgroud)

这种方法行得通,我将控制台项返回到控制台。这样做的缺点是所使用的URL是静态的。我要执行的操作的点是,通过获取API的结果来链接一堆URL,然后是一个URL调用,其中包含了NextPage结果的URL。

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"
});
Run Code Online (Sandbox Code Playgroud)

Dyl*_*ang 5

尝试这个:

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));
      }
    });
  }};
};  
Run Code Online (Sandbox Code Playgroud)

然后您可以调用它:

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