Callback Function Return

Asked

Viewed 64 times

0

In a conventional function I can return a value and treat it outside the function:

var teste;

function funcaoTeste(){
    return 'retorno da funcao teste';
}

teste = funcaoTeste();

console.log(teste);

My question is this: how do I do this same procedure in a callback function and in an asynchronous function?

1 answer

0


I’m not quite sure of your doubt, but I believe that you wish to seek the value of an asynchronous function, I will write a code to try to help you, if not what you seek leave a comment so I can help you,

let’s create an asynchronous function, which returns a value after 5 seconds:

function espera() {
    return new Promise((resolve, reject) => {
        setTimeout(() => resolve("finalizado"), 1000 * 5);
    });
}

now let’s make a high-order Function that gets the function waits as callback and waits for its return:

async function hightOrder(callback) {
    let retorno = await callback();
    console.log(retorno);
}

note that I chose to use Promisse in the first function and async/await on Monday, I did this for didactic purposes, but it is highly recommended that you use only one of the approaches.

Finally we will run the highOrder passing the asynchronous function as callback:

hightOrder(espera);

what’s going on here?

The high-order Function function called hightOrder, receives the callback called wait and execute, but waits for it to be solved, once it is solved, prints in the console its return value.

  • Thank you so much for having responded! Well, that’s basically it, but I still have one question: if I had a variable outside this hightOrder function, how would I make the result of the variable return for it?

  • simply you can return the value for example, you would have the variable var x = 100; outside the function, but within the function you could perform return x;, but you must note that the return of this function will be a promise, so it will be necessary to wait for it to be resolved, with await or with Promisse. I suggest you read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise If I could help you, please locate my post.

  • Excellent! thank you very much.

Browser other questions tagged

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