Thursday, 15 April 2010

Node.js function returns undefined -



Node.js function returns undefined -

i have issues asyncness of node.js.

rest.js var shred = require("shred"); var shred = new shred(); module.exports = { request: function (ressource,datacont) { var req = shred.get({ url: 'ip'+ressource, headers: { accept: 'application/json', }, on: { // can utilize response codes events 200: function(response) { // shred automatically json-decode response bodies have // json content-type if (datacont === undefined){ homecoming response.content.data; //console.log(response.content.data); } else homecoming response.content.data[datacont]; }, // other response means something's wrong response: function(response) { homecoming "oh no!"; } } }); } } other.js var rest = require('./rest.js'); console.log(rest.request('/system'));

the problem ist if phone call request other.js 'undefined'. if uncomment console.log in rest.js right response of http request written console. think problem value returned before actual response of request there. know how prepare that?

best, dom

first off, useful strip downwards code have.

request: function (ressource, datacont) { var req = shred.get({ // ... on: { // ... } }); }

your request function never returns @ all, when phone call , console.log result, print undefined. request handlers various status codes phone call return, returns within of individual handler functions, not within request.

you right asynchronous nature of node though. impossible return result of request, because request still in progress when function returns. when run request, starting request, can finish @ time in future. way handled in javascript callback functions.

request: function (ressource, datacont, callback) { var req = shred.get({ // ... on: { 200: function(response){ callback(null, response); }, response: function(response){ callback(response, null); } } }); } // called this: var rest = require('./rest.js'); rest.request('/system', undefined, function(err, data){ console.log(err, data); })

you pass 3rd argument request function phone call when request has finished. standard node format callbacks can fail function(err, data){ in case on success pass null because there no error, , pass response data. if there status code, can consider error or whatever want.

node.js

No comments:

Post a Comment