Javascript -recursion and asynchronic

Good Day Everyone,

I was wondering if somebody could help me resolve this problem


Please don’t bother about Promise , I only tried to use it solve this problem :wink:

DESCRIPTION: As YOU CAN SEEN FUNCTION takeOnes give you a random number from 1 to 4, AND THIS function uses Recursion.

PROBLEM: WHEN I try to run this code below and function return 1-4 at once not calling itself second or more times everything works, but if it call it at least once than function takeOnes calling another takeOnes return somehow undefined (AT LEAST THAT VALUE IS TAKEN ), IT doesn’t wait until last recursion will return a value. TRY TO RUN THIS CODE AND SEA RESULTS IN CONSOLE --> please refresh page several times to understand what I mean :slightly_smiling_face:

TIP: I DON’t want to change this function takeOnes to do it this task without recursion, I wonder if there is way to wait for final result when you calling it from other function ?

let solveIt = new Promise(function(resolve, reject) {
    resolve( takeOnes() );

    function takeOnes() {
        var oneTwo;
        oneTwo = Math.random();
        oneTwo = (oneTwo*10).toFixed(0); 
    if(oneTwo > 4 || oneTwo < 1) { 
        console.log("once again --> returned undefined now");
        takeOnes(); }
    else {
        return oneTwo;}


You need to return takeOnes() when you call it again recursively, that way it completely exits the function, and removes it from the stack, this is very similar to how you return oneTwo which is your final answer and by doing so you are completely exiting the function

Thanks for your Help ;), I have just added retun takeOnes(); and works as it should be :wink: