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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)