Async/Await, where are you wrong?

Asked

Viewed 526 times

0

const url = 'http://files.cod3r.com.br/curso-js/funcionarios.json'
const axios = require('axios')    

const busca = () =>{
        return new Promise((resolve, reject) =>{
            try{
                const funcionarios = axios.get(url).then(resp => resp.data)
                resolve(funcionarios)
            }
            catch(e){
                reject(e)
            }
        })
     }

    async function getFuncionarios(){


      const funcionarios = await  busca().then(resp => resp)
        return funcionarios
    }

    const fcs = getFuncionarios()

fcs should be loaded with all the functionalities of the url, but only Promise{}. Where is the error ?

axios.get() returns a file, I solve it with the then() and play the result (Resp.data) in the const files and I pass it in the resolve() of my own Promise. In the other function I leave it as async and place await in the busca().then(resp => resp) solving my own promise and talking to wait and then return the result

1 answer

2


If you are using async/await no need to use the then:

const url = 'http://files.cod3r.com.br/curso-js/funcionarios.json';
const axios = require('axios');

const busca = async () => {
  const { data } = await axios.get(url);
};

const getFuncionarios = async () => await busca();

const fcs = getFuncionarios();

As remembered by Sergio in the comments, the return value of a function async is a Promise then to use the value you must use the then or a await:

(async () => console.log(await getFuncionarios()))();
  • 2

    Sorack, the return value of a async is a Promise. In your example fcs is a Promise

  • Friend, you forgot the search() Return, but even with it does not produce the expected result, continue with Promise{<pending>}.

  • @Sergio truth

  • I understood, however, it will always stay in this cycle ? I will never be able to take the value and store it in a variable that does not become a Promise ?

  • @Kevinricci no, always like this.

Browser other questions tagged

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