0

everyone.

I would like to know how can I make JS to wait until my function finishes, to use its retruned value.

I use to do this:

function printHelloWorld(){
    var x = myHolyFunction("Hello");
    console.log(x);
}

function myHolyFunction(y){
    z = y + "World";
    return z;
}

But my current problem is that myHolyFunction recieves an argument, sends it to PHP, and has to wait until PHP sends an answer. I know how to wait for PHP (helped by .done from ajax), but for that moment the console.log line (from printHello) has been executed printing undefined.

The point is that I'm handling so many variables in printHelloWorld that I couldn't simply make this:

function printHelloWorld(){
    var x = myHolyFunction("Hello");
    if(typeof(x) != undefined){
        console.log(x);
    }else{
        setTimeOut(printHelloWorld, 100);
    }
}

Thanks for your help :)

-----Follows almost sure irrelevant information----

Looking in other threads I found something about "callbacks" (I'm not a professional programmer) and I tried something like this:

function printHelloWorld(){
    var i = "!";
    myHolyFunction("Hello", function(j){console.log(j);});
    var k = j + i;
    console.log(k);//I would thank a "HelloWorld!" right here
}

function myHolyFunction(y, callback){
    z = y + "World";
    return callback(z);
}

But it doesn't solves the problem for two reasons: 1) j keeps inside the function and I've read that global variables are not the best option and 2)it doesn't even waits... but executes at the same time. I mean, even if I use a global variable, for the moment it gets the value from myHolyFunction, the line where I declare k would be alredy executed, printing me also "undefined".

  • anything you want to execute after myholyfunction will go in its callback function you have to put your k=..... in function(j) – Arpit Solanki Jul 10 '17 at 08:39
  • Your function is *asynchronous* ("will finish sometime later"). It will never return synchronously. Any caller of that function must also be asynchronous and also can never return synchronously. – deceze Jul 10 '17 at 08:40

0 Answers0