How to save asynchronous function return solved

Asked

Viewed 220 times

-1

To save the result of a solved asynchronous function to a variable to use the result later along the code ?

Example: How do I save function result joinStrings in a variable outside the async function. That, to use it in another part of the code ? That way, how can I have the resolution of the promise saved within the variable reply ?

async function joinStrings(string1, string2) {
    return string1 + ' ' + string2;
}
async function iniciar() {
    await joinStrings('Nayton', 'Sanches').then(resultado => {;
        console.log(resultado);
    });
}

const resposta = iniciar()

console.log(resposta)     // Promise { <pending> }

Edited Question, after obtained answers.

// Código usado apenas para aprender como salvar o resultado de uma função assincrona.
async function unir(nome, sobrenome) {
    return nome + ' ' + sobrenome;
}
async function iniciar() {
    const resposta = await unir('Nayton', 'Sanches')
    return resposta
}
const resposta = iniciar()

//Como é preciso aguardar a resolução de uma função assincrona, ela nunca está disponível imediatamente. Assim, sempre que for preciso usar o retorno dessa função no escopo global é necessário usar o .then
resposta.then(res => console.log(res))

// Como usar em outra função a resposta de uma função assincrona ?
const montarFrase = function () {
    const inicoDaFrase = "Meu nome é "
    const FraseCompleta = `${inicoDaFrase} ${resposta.then(resp => resp)}`
    return FraseCompleta
}
montarFrase.then(resp => console.log(resp))

So, how to use in another function the response of an asynchronous function ?

  • wait for the Function reset with await: const x = await joinStrings..., now if you want to run the code normally and set the result when the Promise retouch, create a variable outside the scope of Function, global for example, and seven the variable inside Function, before Return

  • let resposta&#xA;&#xA;async function joinStrings(string1, string2) {&#xA; return string1 + ' ' + string2;&#xA;}&#xA;async function iniciar() {&#xA; resposta = await joinStrings('Nayton', 'Sanches');&#xA;}&#xA;//iniciar();&#xA;&#xA;iniciar()&#xA;console.log(resposta) So, created the global variable reply outside the scope of Function, however the return was Undefined

1 answer

0

You can only use the await within a function async... if that code runs on the global scope (window, or the root of a module) then you have to wait/use the .then and only then will you have the answer:

const resposta = iniciar()
resposta.then(res => console.log(res))

Interestingly the Deno.js and Node 14.3 (Javascript on the server) support await in the global context... maybe this will be supported in the future in the browser too.


Note: I imagine it was for example, but notice that iniciar does not return anything, nor his .then(

  • returned: Undefined

  • @Nay-ton you saw mine nota? your start function returns nothing...

  • I entered a return. Now, how to use in another function the response of an asynchronous function ?

  • @Nay-ton resposta.then(montarFrase) or resposta.then((result) => montarFrase('Frase', result)). In function montarFrase, just use parameters instead of variables that are outside the function scope.

Browser other questions tagged

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