Search code examples
javascriptfetch-api

Javascript Fetch API - How to save output to variable as an Object (not the Promise)


Please, how can I save output of fetch to a variable - to be able to work with it as with an object?

Here is the code:

var obj;
fetch("url", {
  method: "POST",
  body: JSON.stringify({
    "filterParameters": {
      "id": 12345678
    }
  }),
  headers: {"content-type": "application/json"},
  //credentials: 'include'
})
.then(res => res.json())
.then(console.log)

The final console.log will show an object. But when I tried to save it to variable .then(res => obj = res.json()) than the console.log(obj) will not hold the Object, but the Promise.

Console

Any idea please, how to turn it into an Object saved in the variable?


Solution

  • .json() is an async method (it returns a Promise itself), so you have to assign the parsed value in the next .then()

    var obj;
    
    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then(res => res.json())
      .then(data => {
        obj = data;
       })
      .then(() => {
        console.log(obj);
       });

    Modern async/await equivalent

    You have to await the .json() method.

    async function foo() {
      let obj;
    
      const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')
    
      obj = await res.json();
    
      console.log(obj)
    }
    
    foo();