简体   繁体   中英

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);
  })
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM