0

I am trying to make an api call using fetch. But i am getting a promise in that not the data.If i resolve the promise inside fetch, i get the data not outside. How can i get the result from api to data variable.

export function getAllBooks() {
    var data= fetch('https://api.myjson.com/bins/9paef').then((data) => {
        data.json().then(function (response) {
         return response
        });
    })
    console.log("data",data)
}
pKay
  • 1,832
  • 4
  • 16
  • 23
  • @Quentin This isn't an exact duplicate of the link you provided.We should open up this question. – Ayan Jul 04 '19 at 13:45
  • @Ayan — Both questions are "How can I use a value generated inside a callback, outside the callback and before the callback has executed?". It is a duplicate. A dozen of these get asked every single day, and the duplicate has some very detailed and highly rated answers. – Quentin Jul 04 '19 at 13:46
  • @Quentin This is more with fetch, and the provided link is more with ajax.I agree that the underlying logic is similar.But on an upper level they are a bit different.For beginners, this question can be helpful – Ayan Jul 04 '19 at 13:50
  • There's no practical difference. The answers would be the same. – Quentin Jul 04 '19 at 13:51
  • @Quentin , Yes the answer is similar but when i tried searching for this i didn't get any relevant answers. To get to the original questions that have already asked, i should have searched for "How do I return the response from an asynchronous call? " but this did not cross my mind. So people who are new to JS might find it useful. – pKay Jul 04 '19 at 16:24
  • 1
    @pKay — You seem to have missed the point of closing a question as a duplicate. Google will find this question, then people will get to this page, then they will see the big yellow box at the top of the page and see good answers. – Quentin Jul 04 '19 at 16:42
  • @Quentin thanks for pointing out the original quesitons , it was very helpful. – pKay Jul 04 '19 at 17:03

1 Answers1

1

You can use await wich allows us to wait for the response of an asynchronous request. An example of use is here:

async function getAllBooks() {
  const response = await fetch('https://api.myjson.com/bins/9paef');
  const data = await response.json();
  //console.log('Data', data);
  return data;
}


getAllBooks().then((books) => {
  result = books;

  console.log("Books", result);
});

See it on jsbin.com

Abdulbosid
  • 354
  • 1
  • 2
  • 12