Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch function return Promise <pending>

So my code here return a Promise and since I'm using then syntax I don't know why that happens :-??

fetch('someurltoAJsonFile.json')
  .then(function(response) {
    console.log(response.json());});
like image 748
C. Cristi Avatar asked Feb 12 '19 18:02

C. Cristi


People also ask

What is promise then fetch in JavaScript?

Promise.then fetch is an asynchronous function. What this function returns is a Promise object. This kind of object has three possible states: pending, fullfilled and rejected.

How to return a value from a promise object in JavaScript?

You can use the return value from the Promise object ONLY in a async function. You should do all the stuff that you'd like to do with the return result in a printAddress () async function.

How do I return a promise from an asynchronous function?

Approach: You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need to return the promise as an output from that asynchronous function.

Why is promise pending in console log?

Promise { <pending> } 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.


2 Answers

response.json() in node-fetch library also returns a promise, instead try

fetch('someurltoAJsonFile.json')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  });

you can look up more details about it here

EDIT:

It seems that the returned response wasn't in the valid json, so for the sake of completeness here is a code for text

fetch('someurltoAJsonFile.json')
  .then(response => response.text())
  .then(data => {
    console.log(data)
  });
like image 130
Krzysztof Krzeszewski Avatar answered Sep 17 '22 17:09

Krzysztof Krzeszewski


The function given as then parameter will be executed asynchronously (sometime in the future when your server returns a response), but then itself return Promise immediately (in synchronous way) by its definition

If you want to code looks less nested (more as synchronous code) you can use await but you must opaque whole code with async function

async function load() 
{
  let response = await fetch('someurltoAJsonFile.json');
  let data = await response.json();
  console.log(data);
}
like image 44
Kamil Kiełczewski Avatar answered Sep 19 '22 17:09

Kamil Kiełczewski