javascript - return new Promise() not working in Node.js -


i'm new concept of promises, javascript in general. i'm trying write function in node.js can pass url promise of results.

i have programmed 2 ways. first not work, in can pass url function. second work, in url statically defined. first 1 not work because compiler not think function reason can't figure out, why?

this way doesn't work function getjson not interpreted node function:

var options = { method: 'get',                 url: url,  // dynamically filled argument 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 array in jason called items        }     });   });  // edited original post. had 2 curly braces }}; here accident, why function not being recognized };    getjson.then(function(result) {   console.log(result.items); // "stuff worked!" }, function(err) {   console.log(err); // error: "it broke" }); 

this way work , array of items console. downside of url used static. point of trying chain bunch of url's taking result of api, 1 url call contains url of 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" }); 

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 can call it:

getjson(thedynamicurlgoeshere).then(function(result) {   console.log(result.items); // "stuff worked!" }, function(err) {   console.log(err); // error: "it broke" }); 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -