1

I'm trying to get the result of a fetch in an asynchronous way like this:

var result = await fetch(`/api/collection/get-collection.php?name=${this._name}`, {method: `GET`});
console.log(result.json());

but when I look at the console I get this:

Promise {<pending>}
  __proto__: Promise
  [[PromiseStatus]]: "resolved"
  [[PromiseValue]]: Object
    content: (176) [...]
    extra: {...}
    message: ...
    __proto__: Object

So I feel like when it comes to the console.log the promise is still pending? (there's a tooltip saying "Value below was evaluated just now" so I guess it's updated when the promise is resolved? And of course the code below (not shown here) doesn't work cause it needs the value of fetch's return. And I don't even know how to access PromiseValue.

What is the proper way to make an asynchronous fetch call?

PS: I'm using vanilla JS.

Gaetan L.
  • 649
  • 6
  • 20
  • 4
    `result.json()` returns another `Promise` that you'll need to `await`. – sp00m May 21 '20 at 18:03
  • And please: NEVER let an Promise be uncatched (bad practise). – Kai Lehmann May 21 '20 at 18:05
  • Oh. Okay yeah that's it, can you write an answer so I can validate it? On a side note if you have an advise on how to write a proper asynchronous call (I mean the good practice if there is one). – Gaetan L. May 21 '20 at 18:06
  • @Kai Lehmann okay I'm really new to this (promises and async and so on), if you have a code example of how to write a good asynchonous call that'd be nice. I'm trying to read on the subject but most of it goes over my head. – Gaetan L. May 21 '20 at 18:07
  • @Gaetan L. Check this const fetchPromise = fetch("https://ghibliapi.herokuapp.com/people"); fetchPromise.then(response => { return response.json(); }).then(people => { console.log(people); }); – Harmandeep Singh Kalsi May 21 '20 at 18:09
  • yourPromise.then(data => { //make fancy things}).catch(error => {console.error(error);}).finally(()=>{ //things that will happen after regardless of success or failure}); – Kai Lehmann May 21 '20 at 18:09
  • @Gaetan L. Kai has explained it well . Check this link too . This might help https://javascript.info/promise-error-handling – Harmandeep Singh Kalsi May 21 '20 at 18:12
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – gaaaaaa May 21 '20 at 18:13
  • Why would you mix `async`/`await` with `.then`? I'd go full `async`/`await` if I have access to them. There's no obvious good practices that I'm aware of in this area, just remember that this code still is async (while looking sync), see https://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/, and feel free to close your question :) – sp00m May 21 '20 at 18:13
  • Honestly up until this point I thought async/await was bad and Promises were the new way to go. I thought asynchronous was like old practices and I'm struggling since the beginning of my project to make everything work with .then :D – Gaetan L. May 21 '20 at 18:21
  • 1
    Put simply, async/await is just syntax sugar to make promise-based code looks synchronous. – sp00m May 21 '20 at 19:08

1 Answers1

1

You can do the fetch call using async-await like this.

try {

   const response = await fetch(`/api/collection/get-collection.php?name=${this._name}`, {method: `GET`});

   const result = await response.json()

   // do something with the data
   console.log(data);

} catch(error) {

  // your error handling code

  console.log(error)

}

if you do not want to use async-await then you can use .then to resolve the promise.

 fetch(`/api/collection/get-collection.php?name=${this._name}`, {method: `GET`})
        .then(res => res.json())
        .then(data => {
           // do something with the data
           console.log(data)
         })
        .catch(error => {
            // your error handling code
            console.log(error)
         });

subashMahapatra
  • 6,339
  • 1
  • 20
  • 26