How to expect one javascript function within another?

Asked

Viewed 1,473 times

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));

Note that function 2 sends the sum without having finished the entire internal process, I know that if I put the sum within the settimeout it will wait and give me the result, but function 2 exemplifies a function with various operations, this in another language would wait for the end of function 2, already in javascript this does not occur, how to solve?

  • 1

    You’re doing something asynchronous. Behold

1 answer

1

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

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 the alert(15) is executed only after the alert("hello"), as desired.

  • But then if I remove the callback from inside the settimeout function it will perform the sum first, the example I gave is to show that there is a sequential waiting of operations, I should make a tree of processes with the functions, but I do not know how to do

  • "there is no sequential wait for operations". Exactly, this is the spirit of asynchronous calls. If you need it to be sequential, do not use setTimeout.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.