0

I am getting a weird kind of issue. I have a function getPosts which return a json object, when I run a .map() function on it, I get error TypeError: getPosts(...).forEach is not a function, but when I store the value of getPosts in a variable, such as json1 and then run the .map() function on it, it works perfectly. I don't know why that is happening.

async function getPosts() {
  let posts = await fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(json => {
    return json.slice(0, 5)
  })
}

var json2=["Ike","Ron"];
var i=0;
getPosts().forEach(element => {
  element.first_name=json2[i]; i++;
});

console.log(getPosts())

Error Log

TypeError: getPosts(...).forEach is not a function

result of getPosts stored in var json1 is

let json1 = [
  {
    userId: 1,
    id: 1,
    title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    body: 'quia et suscipit\n' +
      'suscipit recusandae consequuntur expedita et cum\n' +
      'reprehenderit molestiae ut ut quas totam\n' +
      'nostrum rerum est autem sunt rem eveniet architecto'
  },
  {
    userId: 1,
    id: 2,
    title: 'qui est esse',
    body: 'est rerum tempore vitae\n' +
      'sequi sint nihil reprehenderit dolor beatae ea dolores neque\n' +
      'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\n' +
      'qui aperiam non debitis possimus qui neque nisi nulla'
  }
]

when I run the .map() function here, it works fine and I get the expected result

var json2=["Ike","Ron"];
var i=0;
json1.forEach(element => {
  element.first_name=json2[i]; i++;
});

console.log(json1)

expected result is as below and works fine

[
  {
    userId: 1,
    id: 1,
    title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
    body: 'quia et suscipit\n' +
      'suscipit recusandae consequuntur expedita et cum\n' +
      'reprehenderit molestiae ut ut quas totam\n' +
      'nostrum rerum est autem sunt rem eveniet architecto',
    first_name: 'Ike'
  },
  {
    userId: 1,
    id: 2,
    title: 'qui est esse',
    body: 'est rerum tempore vitae\n' +
      'sequi sint nihil reprehenderit dolor beatae ea dolores neque\n' +
      'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\n' +
      'qui aperiam non debitis possimus qui neque nisi nulla',
    first_name: 'Ron'
  }
]

updated code after returning the posts

async function getPosts() {
  let posts = await fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(json => json.slice(0, 5))
  return posts
}

getPosts()
oyerohabib
  • 187
  • 3
  • 16
  • `getPosts()` is a Promise; Promises don’t have a `forEach` method. The Promise is also useless as `posts` is never used, so the result is thrown away. You need `async function getPosts(){ return fetch(`…`).then(`…`).then(`…`); }`, then await `getPosts()` either by using top-level `await` in a module, or by wrapping `(await getPosts()).forEach(`…`);` in another `async` function. – Sebastian Simon Feb 09 '22 at 21:39
  • How can i resolve that. – oyerohabib Feb 09 '22 at 21:40
  • @KillianHuyghe, getPosts() returns this: json.slice(0, 5) – oyerohabib Feb 09 '22 at 21:44
  • @oyerohabib No, it's your last `.then(...)` that returns `json.slice(0, 5)`. The return value of your last then is stored into `posts` when the Promise returns. Then you never return posts. Just add `return posts;` at the end of `getPosts()`, that will move you forward. – Killian Huyghe Feb 09 '22 at 22:00
  • I get this, "Promise { }" – oyerohabib Feb 09 '22 at 22:08
  • I updated the question and you can see the update at the end of the question. – oyerohabib Feb 09 '22 at 22:09
  • 1
    @oyerohabib You have a bug in your code. Check my previous answer https://stackoverflow.com/a/71053394/11392290 I included this question too. – Serge Feb 09 '22 at 23:47

0 Answers0