【问题标题】:Not able to get the values from this function [duplicate]无法从此函数中获取值[重复]
【发布时间】:2020-06-20 02:17:50
【问题描述】:

提取工作正常,但在从提取数据中推送值后,“标题”数组中没有值。

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

【问题讨论】:

  • 您在 title 被 Promise 链处理之前返回它。

标签: javascript json fetch fetch-api


【解决方案1】:

fetch 是一个异步函数,您从 fetch 外部返回标题,因此您的函数将在 fetch 请求完成之前返回标题。

试试这个。

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


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

【讨论】:

  • 为什么不重构代码以在 toto 中使用 async/await 模式。
  • 感谢您的意见,我已添加 async/await。
  • @Sohail - 所以我需要一个全局变量来保存匿名异步调用函数内部的“标题”的值。那你能告诉我怎么做吗?
  • 只需在函数外声明titled 变量let。例如let titled; (async function() { titled = await getdata(); console.log(titled); })();
  • 但是当我将它记录在函数之外时,它会显示“未定义”,但我希望它保留所有值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 1970-01-01
  • 2017-06-21
  • 2011-12-11
  • 1970-01-01
  • 2021-09-29
  • 1970-01-01
相关资源
最近更新 更多