Peder
Peder

Reputation: 53

io.emit not sending return from promise

io.emit('runPython', FutureValue().then(function(value) {
  console.log(value); //returns 15692
  return value;  // socket sends: 42["runPython",{}]
}));

As above, I am trying to send 15692 on io.emit, but the promised function is not returning the value even though I can see the value in the console.

Here is FutureValue():

function FutureValue(){
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);
  })
}

Upvotes: 0

Views: 65

Answers (2)

trincot
trincot

Reputation: 350272

You currently pass a promise as 2nd argument to the emit method, not the resolved value.

Instead, invoke the emit when the promise resolves:

FutureValue().then(function(value) {
  console.log(value); //returns 15692
  io.emit('runPython', value);
});

Or shorter (without the console.log):

FutureValue().then(io.emit.bind(io, 'runPython'));

Upvotes: 1

AVAVT
AVAVT

Reputation: 7133

io.emit('runPython', FutureValue().then(function(value) {
  console.log(value); //returns 15692
  return value;  // socket sends: 42["runPython",{}]
}));

Your emit is not sending the value, it's sending the Promise!

value is only available inside the callback function of then(), which would be called asynchronously after the promise has completed successfully. By the time you emit the event, you only have a Promise in hand and no result yet.

Upvotes: 0

Related Questions