1

I have a module that invokes a service

let getData =  () => fetch("https://jsonplaceholder.typicode.com/posts")
  .then(response => response.json())
  .then(json => (getData = json));

export {getData };

I try to log to console the result (and put it on an HTML page) like this

import { getData } from "./api";


 const app = document.querySelector("#target");
    let data = getData()
      .then(res => res.map(r => r.title).join("\n"))
      .then(res => (data = res));
      console.log(data);
      app.innerHTML = data;

However, I get an unresolved promise like this [object Promise]

I've tried a few variations which also don't work

// none of these work don't work

// .then(async res => data = await res);
// .then(res => (data = Promise.resolve(res)));

Any suggestions as to what I am doing wrong?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
underwater
  • 191
  • 1
  • 11

2 Answers2

0

Firstly, you shouldn't use the second then in getData - that's the result, and it reassigns your variable. Then change some other things in your code - syntax errors and wrong methods mostly:

let getData = () => fetch("https://jsonplaceholder.typicode.com/posts").then(response => response.json());

const app = document.querySelector("#target");
getData()
  .then(res => res.map(r => r.title).join("<br>"))
  .then(res => app.innerHTML = res);
<p id="target"></p>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
-1

i think you have to 'return' response.json() and then exec another then() and also is better to include cathc to see problems

read Making fetch requests https://developer.mozilla.org/it/docs/Web/API/Fetch_API/Using_Fetch

    let getData = () => fetch("https://jsonplaceholder.typicode.com/posts")
.then(function (response) {
    return response.json();
    })
    .catch(function (err) {
        console.log(err);
    });
const app = document.querySelector("#target");
getData()
 .then(res => res.map(r => app.innerHTML += r.title));