0

I am learning some async foundations and callback functions in Javascript And I want to return a random boolean after a random delay I have a function that when invoked returns a callback but I don't get how to just return the testValue from the callback after the setTimeout is resolved.

const returnTestValue = () => {
  const delay = 7000 + Math.random() * 7000;
  const testValue = Math.random() > 0.5;

  return callback => {
    window.setTimeout(() => callback(testValue), delay);
  };
};

The returned callback after calling returnTestValue()

callback => {
  window.setTimeout(() => callback(testValue), delay);
}
FZs
  • 16,581
  • 13
  • 41
  • 50
newDev
  • 97
  • 1
  • 13
  • 1
    This doesn't make a lot of sense. You probably should just take the `callback` as the argument to `returnTestValue`, and not `return` anything (like that function). – Bergi Oct 01 '19 at 21:19
  • But without changing anything about your code you would do `returnTestValue()(x => console.log(x))`. Note that you cannot actually *return* `testValue` from `returnTestValue`. You may find the following useful even if it doesn't answer your question: https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html – Felix Kling Oct 01 '19 at 21:20
  • 1
    Btw, you shouldn't use the terminology "return a value" with asynchronous functions - they cannot `return`, the can just call the callback. – Bergi Oct 01 '19 at 21:20
  • Possible duplicate of [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) – FZs Oct 01 '19 at 21:40
  • 1
    @Bergi Well, technically all functions "return" - - when they are complete they "return" control back to the call stack. And, it's not actually the asynchronous function that calls the callback, it's the asynchronous component that does that (in this case the `window.setTimeout` API). The async function can and does return its data (through the asynchronous API component) to the callback function. – Scott Marcus Oct 01 '19 at 22:01
  • @ScottMarcus Sorry, I was imprecise myself. I should've written "asynchronous functions cannot `return` *the result*". Of course they need to return control back to their caller before the async callback happens. – Bergi Oct 01 '19 at 22:07

1 Answers1

0

You could return a Promise that will resolve with your random boolean after your random delay like so:

const returnTestValue = () => {
  return new Promise(function(resolve) { 
    const delay = 7000 + Math.random() * 7000;
    const testValue = Math.random() > 0.5;
    setTimeout(() => resolve(testValue), delay);
  });
};

and using .then process the result like this: returnTestValue().then(testValue => console.log(testValue));

thehuijb
  • 239
  • 1
  • 12
  • You have to pass a function to `setTimeout`. `setTimeout(resolve(testValue), delay);` should be `setTimeout(() => resolve(testValue), delay);` – Felix Kling Oct 02 '19 at 13:09