0

I'm currently facing this problem where I can't get a parent function to wait for a child function to retrieve some data and then having the parent function return the data.

In my case the child function is a callback of the on method.

const parent = () => {

  ...

  let value;

  child.on('data', (data) => value = data);

  return value;
}

What I presume is happening here is that the parent function returns value before it gets anything assigned to it, thus making value equal to undefined. I am certain that I am recieving the desired data because when I log data within the callback I get the expected output.

So all and all what I would like to do is to make the parent function return the data which the child function recieves. I'm not entirely sure on how to go about from here.

I am very greatful for any help I can get.

Oscar Q.
  • 65
  • 8
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Dec 24 '19 at 00:39
  • Oscar, mwilson has provided the solution. Promise is the way to go here. – Bibberty Dec 24 '19 at 00:44

1 Answers1

3

One quick solution is to change your parent function into a promise. This way, you can wait for the inner function to finish and return that as a result

const parent (child) => {
  return new Promise( (resolve, reject) => {
    child.on('data', data => { resolve(data); });
  });
};

// Usage
function childFunction () {
  // ...
  
  return 'something';
}
parent(childFunction).then( val => console.log(val) );
mwilson
  • 12,295
  • 7
  • 55
  • 95
  • 1
    I have now taken the time to _really_ understand how promises work and it works great. Thank you so much. – Oscar Q. Dec 24 '19 at 01:05
  • Yes, they are awesome. You could do this without promises, but you'd basically have to pass in a call function. promises are better to look at. – mwilson Dec 24 '19 at 01:06