Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why fetch returns promise pending?

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); 
});
like image 628
Max Avatar asked Dec 18 '19 14:12

Max


People also ask

Why is a promise pending?

pending: The promise is in it's initial state, it has not completed it's operation nor has it failed. fulfilled: The operation has completed successfully. rejected: The operation has failed.

How do I resolve a promise pending issue?

The promise will always log pending as long as its results are not resolved yet. You must call . then on the promise to capture the results regardless of the promise state (resolved or still pending): Promises are forward direction only; You can only resolve them once.

Why does fetch return a promise?

The promise resolves to the Response object representing the response to your request. A fetch() promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar).

Does node fetch return a promise?

The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request — as soon as the server responds with headers — even if the server response is an HTTP error status.


1 Answers

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))

like image 157
Jeffrey Devloo Avatar answered Sep 28 '22 04:09

Jeffrey Devloo