fetch function return Promise <pending>

二次信任 提交于 2020-05-08 07:18:07

问题


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());});

回答1:


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



回答2:


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



回答3:


Debating whether or not this qualifies as an answer, but I ran into a similar situation today that led me to this question even though my problem ended up being environment related.

If you are seeing promise pending and your code is correct and you spend way too much time trying to figure out why the console.log isn't showing, double check that you have "Info" turned on in chrome's dev tools. I only had warnings turned on so I wasn't seeing my console.log.



来源:https://stackoverflow.com/questions/54656223/fetch-function-return-promise-pending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!