简体   繁体   English

未捕获(承诺)类型错误:

[英]Uncaught (in promise) TypeError:

I am trying to add numbers from 0-99 to myData function so it prints all of my users with one click.我正在尝试将 0-99 的数字添加到 myData 函数中,以便一键打印我的所有用户。 But I'm getting an error.但我收到一个错误。

Error: index.js:14 Uncaught (in promise) TypeError: Cannot read property 'userId' of undefined at index.js:14错误: index.js:14 Uncaught (in promise) TypeError: cannot read property 'userId' of undefined at index.js:14

function number() {
    for (let i = 0; i < 100; i++) {
        i;
    }
}

const myData = () =>  {
    fetch('https://jsonplaceholder.typicode.com/posts?fbclid=IwAR2aHkMfSVPYV3va38MKu-jOahl9G8UzyPJ1Dd67EyskMPZMw1gN9xi-AUg')
    .then(response => {
        return response.json();
    })
    .then(users => {
        document.getElementById('demo').innerHTML += `
        User ID: ${users[number()].userId}<Br> 
        ID: ${users[number()].id}<br> 
        Title: ${users[number()].title}<Br>
        Desc: ${users[number()].body}`;
    })
}

It's not clear what you hope the number() function will do.不清楚您希望number()函数会做什么。 As you have it in the question it will run the for-loop then exit the function with a return value of undefined .正如您在问题中所拥有的那样,它将运行 for 循环,然后以undefined的返回值退出函数。 Adding return i will cause it to return zero and exit the loop immediately.添加return i将导致它返回零并立即退出循环。

If your intent is to set the demo id's innerHTML to have all users, then you need to have the actions within the loop like this:如果您的意图是将demo id 的 innerHTML 设置为拥有所有用户,那么您需要在循环中执行如下操作:

.then(users => {
  let allUsersHtml = "";
  for (let i=0; i<users.length; i++) {
    allUsersHtml += `
    User ID: ${users[i].userId}<br> 
    ID: ${users[i].id}<br> 
    Title: ${users[i].title}<br>
    Desc: ${users[i].body}`;
  }
  document.getElementById('demo').innerHTML = allUsersHtml;
})

This assumes that the users data coming back is an Array object.这假设返回的users数据是一个Array对象。

The main problem with your first attempt is in understanding how functions operate.第一次尝试的主要问题是理解函数的运行方式。 They can only return one thing each time they are called.每次调用它们时,它们只能返回一件事。 Just because they include a for-loop doesn't mean they'll cause any repeating in the functions that call them.仅仅因为它们包含一个 for 循环并不意味着它们会在调用它们的函数中引起任何重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM