Why fetch returns promise pending?

36,439

Solution 1

A fetch() is a network operation. To avoid hanging until we get a reply from the network, we defer it to the background and give ourselves the promise that it will complete eventually.

So fetch(url).then((data) => data.json()) means that we fetch the url, wait for data to come in, get the json representation of the data and wait for that too (data.json() is a promise too)

Until we get a result, the promise is in the pending state. The server hasn't replied to our request yet.

-- Reading the comments, it might be nice to add a error handler as that is why the current fetch is supposedly not doing anything: fetch().then((data) => data.json()).catch((error) => console.log(error))

Solution 2

Promises are a way to allow callers do other work while waiting for result of the function.

See Promises and Using Promises on MDN:

A Promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation completed successfully.
  • rejected: meaning that the operation failed.

The fetch(url) returns a Promise object. It allows attaching “listener” to it using .then(…) that can respond to result value (response to the request). The .then(…) returns again Promise object that will give result forward.

async and await

You can use JS syntax sugar for using Promises:

async function my_async_fn(url) {
    let response = await fetch(url);
    console.log(response); // Logs the response
    return response;
)

console.log(my_async_fn(url)); // Returns Promise

async functions return a Promise. await keyword wraps rest of the function in .then(…). Here is equivalent without await and async:

// This function also returns Promise
function my_async_fn(url) {
    return fetch(url).then(response => {
        console.log(response); // Logs the response
        return response;
    });
)

console.log(my_async_fn(url)); // Returns Promise

Again see article on Promises on MDN.

Solution 3

As one of the upper comments said, fetch() is a promise that calls .then() when the request is handled by the network. The parameter in this callback is another promise that calls $.then() when we get the response from the server.

Maybe you should try something like this:

fetch(res.url)
    .then(function(serverPromise){ 
      serverPromise.json()
        .then(function(j) { 
          console.log(j); 
        })
        .catch(function(e){
          console.log(e);
        });
    })
    .catch(function(e){
        console.log(e);
      });

or in lambda notation:

fetch(res.url)
    .then((serverPromise) => 
      serverPromise.json()
        .then((j) => console.log(j))
        .catch((e) => console.log(e))
    })
    .catch((e) => console.log(e));

This is the first time I post here in StackOverflow, so please let me know if I made any mistake or you have any sugestions, thanks!

Share:
36,439
Max
Author by

Max

Updated on July 09, 2022

Comments

  • Max
    Max almost 2 years

    I am using fetch to get data but it keeps returning promise as pending. I've seen many posts regarding this issue and tried all the possibilities but didn't solve my issue. I wanted to know why the fetch returns promise as pending in brief what are the possible cases where fetch returns pending status?

    My piece of code for reference:

    fetch(res.url).then(function(u){ 
        return u.json();
    })
    .then(function(j) { 
        console.log(j); 
    });