Question:
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 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 wait for the end of function 2, but in javascript this does not occur, how to solve it?
Answer:
A simple way to work around this problem is to work with callbacks
. Basically, a function that will be executed when an operation completes. In your case, instead of waiting for the return of fTeste1
to call the alert
function, you can pass it as a callback
, as in the code below, indicating: when it fTeste2
the execution of 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 running the code, you will see that the alert(15)
is only executed after the alert("hello")
, as desired.