【问题标题】:Trying to retrieve json informations in a function with Fetch API and then trying to use them in another function尝试使用 Fetch API 在函数中检索 json 信息,然后尝试在另一个函数中使用它们
【发布时间】:2018-11-26 04:19:43
【问题描述】:

我需要从一个 URL(其中包含 JSON 中的信息)中获取一些关于多个对象的信息。 所以我写道:

static fetchObj(){
fetch("http://localhost:1337/objects")
.then(callback => { 
return callback.json();
})
.then(data => {
console.log(data);
});
}

在这里我可以检索我需要的东西并安慰他们以确保确定。

然后我必须在另一个按 ID 查找这些对象的函数中使用这些数据:

static fetchObjById(id) {
      MyClass.fetchObj()
      .then(
          for(var i=0; i<data.id.length; i++){
            if(data[i].id == id)
              console.log("found");
            else
              console.log("not found");
          }
   }

但它根本不起作用..我尝试了几种方法但没有..希望有人可以帮助我:)

【问题讨论】:

  • 不要只是 logdata 中的 fetchObj 而是返回它 - 以及 return 函数的承诺。在fetchObjById 中,您需要将一个以data 作为参数的回调函数传递给then - 传递循环不是有效的语法
  • 你的语法错误。传递给then() 的参数必须是函数。
  • 你应该像MyClass.fetchObj().then(data =&gt; {for....}一样拥抱你的循环
  • 现在我写了这个:static fetchObj(){ return fetch("http://localhost:1337/objects") .then(callback =&gt; { return callback.json(); }) .then(data =&gt; { return data; }); } static fetctObjById(id) { MyClass.fetchObj() .then( data =&gt; { data.forEach(d =&gt; { if(d.id == id){ console.log("found: "+ d.name); } else console.log("not found"); }) }) } 它似乎有效,但我不知道它是否正确。我添加了一些回报..

标签: javascript json ecmascript-6 promise fetch-api


【解决方案1】:

then() 需要一个函数。您可以通过该函数的单个参数访问 Promise 的结果数据,使用箭头函数很容易实现。

另外,我建议您放弃显式 for 循环并研究声明式编程。与then() 类似,在数组上调用forEach() 可以让您使用箭头函数访问每个元素。对我来说,这更具可读性。

最后,可以稍微简化console.log 调用,方法是首先声明打印消息应该是什么(使用三元运算符),然后使用该消息调用一次console.log

const fetchObjById = (id) => {
  MyClass.fetchObj()
    .then(data => {
        data.forEach(d => {
          const message = d.id === id
            ? 'found'
            : 'not found';
          console.log(message);
        })
      }
}

【讨论】:

  • 感谢您的回答,我在第一条评论下发表了评论 :) 我尝试添加 foreach 语句以消除其他临时变量 i :)
  • 没有 cmets 的代码是没用的。如果你解释你做了什么以及你为什么这样做,你的回答对每个人都会更有帮助。
  • @FelixKling 我添加了一些 cmets。
【解决方案2】:

这也是一种查找id的方法。

var id = 4;
function fetchObjById(data) {
    console.log(data);
    for(var i = 0; i < data.length; i++){
        if(data[i].id === id) {
            console.log('found');
            break;
        }
    }
}

var myData;
fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(data => myData = data)
  .then(() => fetchObjById(myData));

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 1970-01-01
    相关资源
    最近更新 更多