Ways to extract JSON data from a promise

Snippet:

fetch(`https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=++++++++++&tags=obama&format=json&extras=url_m&nojsoncallback=true`, {
    method: "GET",
    headers : { 
      'Content-Type': 'application/json',
      'Accept': 'application/json'
     }
  }).then(response => {
    console.log(response.json())
  })

Result:

Promise {_40: 0, _65: 0, _55: null, _72: null}

Answer №1

Here is an additional method to consider:

fetch(...).then(resp => resp.json()).then(data => ...)

It's important to note that fetch will only throw an error on network errors. If you want it to reject the Promise for scenarios like a 500 response, you'll need to inspect the status code and trigger an error:

fetch(url)
  .then(resp => {
     // You must define the function that checks the status code here
     if (http_response_ok(resp.status)) {
       return resp.json();
     } else {
       throw new Error(`Received ${resp.status}`);
     }
  }).then(data => {
     // Success path
  }).catch(err => {
     // Failure path
  });

Answer №2

Waiting for the reply is an option:

fetch(url, options).then(async (response) => {
  const result = await response.json();
  console.log(result)
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can be taken to resolve an ESLing error in this situation?

Check out this code snippet: <template v-if="isTag(field, '')"> {{ getItemValue(item, field) ? getItemValue(item, field) : '&#8211'; }} </template> An issue has been identified with the above code: Er ...

Tips for adjusting the size of a three.js object without changing its position

I'm working on animating a sphere made up of dots, and I'm facing a challenge. I want each dot to remain on the surface of the sphere while it resizes. Currently, I am attempting to scale the mesh or geometry of a specific point on the surface, b ...

Retrieve all exports from a module within a single file using Typescript/Javascript ES6 through programmatic means

I aim to extract the types of all module exports by iterating through them. I believe that this information should be accessible during compile time export const a = 123; export const b = 321; // Is there a way to achieve something similar in TypeScript/ ...

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

What is the process for removing an item from an array that is stored in the backend server?

Apologies for my lack of experience in coding, but I encountered an issue where clicking on the item redirected me to a page and resulted in an error instead of deleting it. I attempted to delete the item using the product ID, but it was not successful. Ev ...

Floating above a surface to manipulate a title

Wondering if it's possible to achieve this without JavaScript, but that would be the ideal scenario. Here's a snapshot of how my page is structured: ____________________________ | TITLE | |This is a fixed header. I wa ...

Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive. I have managed to store the string using the following code snippe ...

How to retrieve data from a JSON file in Angular 2 using the http get

I am encountering an issue while trying to access a json file using http get. The error message I receive is as follows: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterable ...

Issue: Unable to locate the "es2015" preset in relation to the given directory

I encountered an issue while attempting to use babel. Error: Couldn't find preset "es2015" relative to directory webpack.config.js module.exports = { entry: './main.js', ourput: { path:'./', filename:&a ...

Error message appears when attempting to duplicate vertices in a THREE.Geometry object: 'Vector is not defined'

I am attempting to dynamically add new faces to a mesh, but I keep encountering a console warning: THREE.BufferAttribute.copyVector3sArray(): vector is undefined Despite the warning, this example successfully generates a single triangle that is a repli ...

Preventing the mysql server called by php from running when the website is refreshed

My local website runs by querying a mysql database using inputs from an html form. The form values are passed to php via jQuery to execute the query. Is there a way to send a command to the mysql server to terminate the query if the web page is refreshed? ...

Execute a PHP function when a post is clicked using JavaScript

I have a script that shows an image depending on database results. When a user clicks the image, it changes to a new one. The green_star signifies that both $user_id and $thedb_id are in the database, while the grey_star indicates they are not. I want to b ...

The delay between initiating a Next JS route by clicking and the corresponding page actually loading

Just launched my website at this link: I am experiencing a delay of up to 2 seconds between clicking the header links and the page loading. The site works fine in development and on localhost, so I'm not sure why there's such a slowdown on the l ...

Converting a string into a JSON object using Node.js

Trying to retrieve a sample json file using fs.readFile and fs.read in nodejs. Here is the json test file being read: { "HttpTestResponse": [ { "title":"testTitle2", "id": 2, "name":"testName3" ...

Attempting to import a 3D model in the format of .glb

Encountered error in console: Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../". Attempting to load a 3D model, here are my index.html and 3dmodel.js files. Am I overlooking some ...

Using Javascript/HTML to enable file uploads in Rails

I'm currently facing an issue with uploading and parsing a file in Rails, as well as displaying the file content in a sortable table. I followed a tutorial on to get started. This is what my index.html.erb View file looks like: <%= form_tag impo ...

Encountering an issue with extending the MUI color palette, receiving a "reading 'dark'" error due to properties of undefined

Encountering an issue when trying to expand the MUI color palette—getting this error instead: Error: Cannot read properties of undefined (reading 'dark') Take a look at my theme.ts file below: const theme = createTheme({ palette: { pri ...

Creating real-time chat using Node.js

I am looking to create a live chat feature using node js. Can someone provide guidance on how to achieve this? Here are the use cases I have determined: Users will have the option to click on a link or icon labeled 'Online chat support' on the ...

What is the best way to compare a JSON object and a string in JavaScript?

Currently, I am working on developing the website layout for . Most of the data retrieval and display have been successful so far. However, when attempting to filter my search results to show only stop names associated with Subways, I encountered some err ...

Invoking a JavaScript function using jQuery's AJAX

I'm currently working with jQuery and Ajax. Within my MainFile, I have the following code: <html> <head> <script src="Myscript.js"> </script> <script type="text/javascript"> $(doc ...