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?
– Robert Ferreira
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 performreturn 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, withawait
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.– Daniel de Andrade Varela
Excellent! thank you very much.
– Robert Ferreira