Get fetch return with await/async

Asked

Viewed 490 times

-1

recebe();   

async function recebe(){

   const {url} = await pegaValores();

   console.log(url);
}

async function pegaValores(){

    return fetch('http://www.mocky.io/v2/5dba68fb3000007400028eb5')
        .then(response=>response.json())
        .then(data =>{return data})
}

In the console.log(url) is returned undefined, I’d like you to return the object.

  • Always beware of async and asynchronous API concatenations like the Fetch API. How to take Alores is async and returns a fetch the catch awaitValores() will wait just for the fetch to be returned and not the fetch result, so url is as Undefined.

1 answer

3

James,

I ran some tests and got the following results:

  • Accessing this mocky.io API without using HTTPS generates some exceptions during the use of fetch, therefore it will be necessary replace http with https:
      fetch('https://www.mocky.io/v2/5dba68fb3000007400028eb5');
  • You create the constant as follows: const {url}, I didn’t understand Why, but so it doesn’t work, you could just remove the keys in that stretch:
      const url = await pegaValores();
  • Finally in the Value function, as it is a function asynchronous, you can use fetch with await:
      await fetch('https://www.mocky.io/v2/5dba68fb3000007400028eb5')

At the end the code was as follows:

recebe();   

async function recebe(){
  const url = await pegaValores();

  console.log(url);
}

async function pegaValores(){
  return await fetch('https://www.mocky.io/v2/5dba68fb3000007400028eb5').then( result => result.json());
}

If you want to test, here’s an online example: https://repl.it/repls/VisibleDarkredTechnician

  • If I want to get a specific login value I still can’t

  • Yes, this API returns an array with several objects, take a look at this example where the login in the console is printed: https://repl.it/repls/BriskStickyGnuassembler

  • Thank you so much for your help

Browser other questions tagged

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