0

I need to request data from my REST server to populate my UI (frontend). In doing so, I need to request some data from my and other servers. One such request is to get a list of states (provinces). I use fetch() and .json() to do this.

I see there are a few questions on SO addressing this issue mentioned below (here, here and a few more), however attempting their solutions/suggestions did not solve my problem.

e.g.

fetch("http://localhost:3443/app/location/provinces").then(e => e.json()).then(console.log);

Naturally fetch() being a network operation returns a promise, or I can use it with await & async. Also, .json() is also a promise. Since then() is called by resolve(data) to proceed to the next then() and .catch(error) processes reject(error), the request above should make sense.

Problem:

However, on each call to:

fetch("http://localhost:3443/app/location/provinces")
    .then(e => e.json())
    .then(console.log)
    .catch(console.warn);

I get a Promise {<pending>}. Since it is the case, I tried the same with an async/await impl and receive the same "error":

(async () => {
    let l = await fetch("http://localhost:3443/app/location/provinces");
    console.log(l);
})();

What am I doing wrong/missing?

CybeX
  • 2,060
  • 3
  • 48
  • 115
  • 2
    Thats not an error. Its your REPL showing the result of the last expression. – tkausl Aug 17 '20 at 00:14
  • @tkausl so strange, simply pressing up and running the exact same request again works (all the time, the rest server has been running on localhost)...eh? – CybeX Aug 17 '20 at 00:17
  • 2
    The await version is missing another await for `let data = await l.json()`. The then version looks fine – charlietfl Aug 17 '20 at 00:23
  • @charlietfl quite right indeed, thanks for the addition – CybeX Aug 17 '20 at 00:26
  • So, `fetch()` returns a pending promise. That's what it does. And `fetch().then()` returns a pending promise. You have to either use the result inside a `.then()` handler or use `await` on that pending promise to get the value from it. – jfriend00 Aug 17 '20 at 00:56

0 Answers0