Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch return Promise state: pending

I test the fetch API with jsonplaceholder URL, but my function returns "Promise State: Pending", and I don't understand why :

function getUsers(url) {
  return fetch(url)
}

const users = getUsers(`https://jsonplaceholder.typicode.com/users`);

users.then(response => {
  console.log(response.text());
});

I think the problem is because of asynchronous/synchronous methods?

like image 410
Stéphane R. Avatar asked Apr 21 '17 10:04

Stéphane R.


People also ask

Does fetch return a promise?

It returns promise still. here is my code. but when i simply use fetch and then it works fine. I can’t view the code using the link you provided. It only shows me the finished app.

Why is my promise in a pending status in JavaScript?

It's happening because the Javascript code always executes synchronously, so the console.log () function starts immediately after the fetch () request, not waiting until it is resolved. In the moment when console.log () function starting to run, a Promise that should be returned from a fetch () request is in a pending status.

How to return a JSON response from a promise?

Remember that the response.json () also returns a promise. You would need to either await or then the json parsing too. fetch (url) .then (response => response.json ()) .then (json => console.log (json));

What is a promise in JavaScript?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. A Promise may be in one of the following states: One of the most widely used examples of asynchronous operations in Javascript is a Fetch API. The fetch () method returns a Promise. Assume that we fetch some data from a backend API.


1 Answers

I think the problem become asynchrone/synchrone method ?

Yes. You've (mostly) correctly consumed the original fetch() promise, but text() also returns a promise. So:

users.then(response => response.text()) // 1
     .then(json => {                    // 2
          console.log(json);
     })
     .catch(error => {                  // 3
          // handle error
     });

fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.text())      // 1
     .then(json => {                    // 2
          log("typeof json: " + typeof json);
          log(json);
     })
     .catch(error => {                  // 3
          // handle error
     });

function log(msg) {
  var p = document.createElement("pre");
  p.appendChild(document.createTextNode(msg));
  document.body.appendChild(p);
}

At #1 above, we respond to the successful resolution of the fetch() promise by starting the process of reading the body text, returning the promise from text().

At #2 above, we respond to the successful resolution of text()'s promise by using the resulting text (a string containing JSON).

At #3 above, we handle an error from either the original fetch() or the text() promise by doing something with it.

Always be sure to handle promise rejections. If you don't, they're unlike unhandled exceptions. They're reported to the console, and some environments (like recent versions of Node) terminate on unhandled rejections.


Since you're requesting JSON, you might want to use json() rather than text() so you both read and parse it:

users.then(response => response.json())
     .then(arrayOfUsers => {
          console.log(arrayOfUsers);
     })
     .catch(error => {
          // handle error
     });

fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
     .then(arrayOfUsers => {
          log("typeof arrayOfUsers: " + typeof arrayOfUsers);
          log("arrayOfUsers.length: " + arrayOfUsers.length);
     })
     .catch(error => {                  // 3
          // handle error
     });

function log(msg) {
  var p = document.createElement("pre");
  p.appendChild(document.createTextNode(msg));
  document.body.appendChild(p);
}
like image 176
T.J. Crowder Avatar answered Sep 23 '22 08:09

T.J. Crowder