Returning data from on "close" event

Posted on
  • Hi everyone!

    I have run into this problem and I am out of ideas.
    So in my project, the idea is that the device can register itself in my system.
    The device need to send the get request, and in return the access key is send back to the device.
    But I have problem to get the access key because of the asynchronous nature of the request.

    My code is:

     var accessKey;
    
    function registerDevice() {
      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() {
           resData = JSON.parse(resData);
        });
        }).end();
       return setTimeout(function () {
         resData.access_key;
         console.log('timeout', resData.access_key);
         return resData.access_key;
       },10000);
    }
    
     accessKey = registerDevice();
     console.log(accessKey);
    
    

    And after running it I always get the undefined object.
    I need the access key for later use, to add it to the header in other requests, but I have no idea for now, how to return it from the registerDevice(). Also the console.log() with 'timeout' is returning the valid access key.

    Any help will be mostly appreciated.

  • 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;
      console.log(accessKey);
      // ...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() {
            handleAccessKey(JSON.parse(resData).access_key);
        });
        }).end();
    }
    
    registerDevice(acceptAccessKey);
    

    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'...

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Returning data from on "close" event

Posted by Avatar for user97487 @user97487

Actions