0

Working in node.js and trying to get node to run python-shell, calculate a value and then return the answer to computePython() as an object with key result.

How do I get message to return to result: FutureValue() ? console.log(message) works within .on('message'..

function computePython(){
  return {
  result: FutureValue() // I want message from FutureValue() to show up here
  };
}

function FutureValue(){
  var rate = 0.05;
  var nper = 10;
  var pmt = 100;
  var pv = 100;
  var result;

  new PythonShell('future_value.py', jsc(options, {
    args: [rate, nper, pmt, pv]
    }))
    .on('message', function (message) {
       console.log(message); //works
       return message;
    });
  }
Peder
  • 53
  • 1
  • 4
  • I think you should use a [Promise](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise). – dodov Feb 25 '17 at 10:25

1 Answers1

1

You can't because this processing is asynchronous, you can use Promise to make your code more clear and reusable :

function computePython(){
  getFutureValue().then(function(value) {
      // do what you want with value here
  });
}

function getFutureValue(){
  var rate = 0.05;
  var nper = 10;
  var pmt = 100;
  var pv = 100;
  var result;

  return new Promise(function(resolve, reject) {
    new PythonShell('future_value.py', jsc(options, {
        args: [rate, nper, pmt, pv]
    }))
      .on('message', resolve);
  })
}
Freez
  • 7,208
  • 2
  • 19
  • 29
  • still struggling, console.log(value) works, but the return value ends up with {"result"; {}} any ideas? function computePython(){ return { result: FutureValue().then(function(value) { console.log(value); //works return value; //returns empty }) }; } – Peder Feb 25 '17 at 10:50
  • You want to say that you receive the message from PythonShell execution but it is empty => `{result: {}}` ? – Freez Feb 25 '17 at 11:01
  • Yes, so I did like you said and get the message from PythonShell to computerPython. When I run computePython with console.log(value) and return value in the //do what you want with value here, the console.log shows the value, but the return value returns undefined. – Peder Feb 25 '17 at 12:17
  • Could it be because I emit it before its done calculating? Perhaps I need to create another promise: io.emit('runPython', computePython()); – Peder Feb 25 '17 at 13:06