How do I expect a javascript function inside another?

3

I have the hypothetical situation:

function fTeste2(valor) {
  setTimeout(function() {
    alert("Hello");
  }, 3000);
  return valor + 5;
}

function fTeste1(valor) {
  return fTeste2(valor);
}

alert(fTeste1(10));

Notice that function 2 sends the sum without completing the whole internal process, I know that if I put the sum inside the settimeout it will wait and give me the result, but function 2 exemplifies a function with several operations, this in another language would expect the termination of function 2, already in javascript this does not occur, how to solve?

    
asked by anonymous 08.02.2017 / 17:02

1 answer

1

A simple way to handle this problem is to work with callbacks . Basically, a function that will be executed when an operation is finished. In your case, instead of waiting for the return of fTeste1 to trigger the alert function, you can pass it as callback , as in the code below, indicating: when you quit running fTeste2 , execute alert with the passed parameter.

function fTeste2(valor, callback) {
  setTimeout(function() {
    alert("Hello");
    callback(valor + 5);
  }, 3000);
}

function fTeste1(valor, callback) {
  fTeste2(valor, callback);
}

fTeste1(10, alert);

When executing the code, you will see that alert(15) only executes after alert("hello") , as desired.

    
08.02.2017 / 17:23