-2

I am trying to write a simple, portable function where I can pass in an object.property and set its value from the result. Simple example:

var myFunction = function (result){ 
  var data;
  //get some data
  return result = data;
};

myObject.someData;
myFunction(pass reference to key of myObject.someData here)

I want to pass reference to key of myObject.someData here. Brownie points for also declaring it here instead of line above.

Now for my actual code:

var configurations;
var oldServer;
//make a call to get details of old server here

//helper function to stream json into a variable
var streamToString = function(stream, result) {
  var data = '';
  var chunk;

  stream.on('readable', function() {
      while ((chunk=this.read()) != null) {
          data += chunk;
      }
  });
  stream.on('end', function() {
    data = JSON.parse(data);
    return result = data;
  });
}

//declare shadowsocks as a property, so it can be passed as a param
configurations.shadowsocks;

//
streamToString(sequest.get('root@'+ oldServer[0].networks.v4[0].ip_address, '/etc/shadowsocks-libev/config.json', {
  privateKey: sshKey,
  readyTimeout: 20000
 }, function (error, stdout) {
   if (error) {
     throw error;
   }
 }), configurations.shadowsocks
);

I know I can do this the "wrong way" by doing:

 stream.on('end', function() {
        data = JSON.parse(data);
        return configurations.shadowsocks = data;
      });
    }

but then it's not portable. I would like to make this portable.

Kydan
  • 3
  • 1
  • 3

1 Answers1

1

What you're asking for is not possible in JavaScript. The best you could probably do is to pass both the object and the property name to be set. For example:

function streamToString(stream, result, resultKey) {
  var data = '';
  var chunk;

  stream.on('readable', function() {
      while ((chunk=this.read()) != null) {
          data += chunk;
      }
  });
  stream.on('end', function() {
    data = JSON.parse(data);
    result[resultKey] = data;
  });
}

Then use it like:

streamToString(/*...*/, configurations, 'shadowsocks');

I should also point out that unless you're doing this as a one-off task and don't care when it completes, you should instead use a callback that gets called with the value, and then set the property to that value in the callback. That way you will know when the property has been set and is ready for use.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Yes, I thought of this solution, but thought it was rather hack-ish and thought there must be a better way. Seems it will require a bit of a hack. – Kydan Mar 17 '16 at 05:07