Call function only when the previous one closes

Asked

Viewed 56 times

0

i have 2 functions being called within another, the problem that the second function depends on some elements that comes from the first function. The 1° function makes an ajax request that takes a certain time in seconds, and the problem is there. This going to second function without first closing the first, and this hinders the functioning of the second function. Example:

function gerador(){
          funcao1();
          funcao2();
 }

has some way of calling function 2 when closing function 1? remembering that I can not change the structure of functions, I can only call them. So I have to have a solution outside of them.

  • What you describe is a case of XY problem. AJAX has its own mechanism for you to detect the success of the request and execute something (onreadystatechange ). One searched by AJAX here on the site will have examples. Please provide a [mcve] of the problem if the current site posts are not sufficient. Links to better understand how Sopt works: [Tour], [Ask], Manual on how NOT to ask questions and [Help]

1 answer

1


Usually an asynchronous function will have to make use of either callback, or of promise.

Since the question was not specified what the case is, I will have to use a generic example.

If your function uses callbacks, you will probably have to pass the funcao2 as a parameter for the funcao1, so when function 1 finishes running, it can invoke function 2 to be executed immediately afterwards:

function gerador() {
    funcao1(retornoDaFuncao1 => funcao2(retornoDaFuncao1));
}

Now if you are working with Promises, you can utilize the callback in method then to invoke the function 2:

function gerador() {
    funcao1().then(retornoDaFuncao1 => funcao2(retornoDaFuncao1));
}

Or use the modifier async in its function, which allows you to pause it until a file has finished running with the command await. Note that this is only possible if the return of function 1 is an object of type Promise:

async function gerador() {
    var retornoDaFuncao1 = await funcao1();
    funcao2(retornoDaFuncao1);
}

Browser other questions tagged

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