Not able to get the values from this function

Hrithik Anchaliya :

The fetch works fine, but the "title" array has no values in it after pushing the values from the fetch data.

    function getdata(){
    const title = [];
    const body = [];
     const url = 'https://jsonplaceholder.typicode.com/posts';
      fetch(url)
     .then(response => response.json())
     .then(data => {
        //  console.log(data)                        /*This works just fine*/
         data.forEach(posts => {
            title.push(posts.title)
            body.push(posts.body)
            })
     })
    //  const onlytentitle = title.slice(0,9);     
    //  return onlytentitle;
        return title;     
}
const titled = getdata();
console.log(titled);
Sohail :

fetch is an async function and you are returning title from outside the fetch, so your function will return the title before the fetch request complete.

Try this.

function getdata() {
  const title = [];
  const body = [];
  const url = "https://jsonplaceholder.typicode.com/posts";
  return fetch(url)
    .then(response => response.json())
    .then(data => {
      data.forEach(posts => {
        title.push(posts.title);
        body.push(posts.body);
      });
      return title;
    });

}
(async function() {
  const titled = await getdata();
  console.log(titled);
})();


With async/await

async function getdata() {
  const title = [];
  const body = [];
  const url = "https://jsonplaceholder.typicode.com/posts";
  let response = await fetch(url);
  let data = await response.json();
  data.forEach(posts => {
    title.push(posts.title);
    body.push(posts.body);
  });
  return title;
}
(async function() {
  const titled = await getdata();
  console.log(titled);
})();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31767&siteId=1