• Do not understand completely what you try to do, but lines 22..26 look to me misplaced... they should be between line 19 and 20. Furthermore, your line 22 returns the handle of the timeout right after invocation of registerDevice()... way before http request has even been made or has started... and line 23..25 trip after 10 seconds of registerDevice() invocation no matter whether close and line 19 has or has not happened yet. If not yet, you get error, because String does not understand / has no property named access_key. If received, your return in line 25 goes void... because it is deferred / happens on timeout and nothing is there to receive that return value...

    Since things are async, it would be better to pass a callback function with your registerDevice() function. That callback function is a peer of registerDevice and accepts one argument: the result of JSON.parse(resData).access_key.

    Something like that:

    // accessKey.js
    var accessKey;
    function acceptAccessKey(key) {
      accessKey = key;
      // ...here goes what follow reception of access key
    function registerDevice(handleAccessKey) {
      var options = {
        host: this.server_address, // host name
        port: 8080,            // (optional) port, defaults to 80
        path: '/sensor/register',           // path sent to server
        method: 'GET',
        headers: {
          'Accept' : 'application/json',
          'Content-Type' : 'application/json',  }
      var resData = "";
      this.http.request(options, function (res) {
          res.on('data', function (data) {
            resData += data;
          res.on('close', function() {

    I assume that this in line 14 knows about http.... and I conclude that registerDevice() is invoked in that context... (method ?).

    In your whole code Promise may work nicely... then you can sequence all these async activities without ending up in callback hell...

    When using Promise resolution in close, you could logically talk about 'returning from close'...


Avatar for allObjects @allObjects started