@ubbe_lodbroke

Объясните мне кто-нибудь, почему в методе renderUsers() игнорируется forEach()?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>lesson3</title>
    <style>
        .user-list{
            width: 900px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
        }

        .user{
            width: 200px;
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <button id="btn-show-users" >Show Users</button>
    <div class="user-list" id="user-container"></div>
    <script>
        class UserList{
            constructor(url, container){
                this.url = url;
                this.container = container;
                this.allUsers = [];
            }

            renderUsers(){
                this.allUsers.forEach(userInfo => {
                    console.log(userInfo);
                    const user = new User(userInfo);
                    this.container.insertAdjacentHTML("beforeend", user.render())
                })
            }

            getUsers(){
                this.appleUsers()
                    .then(result => this.allUsers.push(...result))
                    .catch(err => console.error(err));

                this.renderUsers()
            }

            appleUsers(){
                return new Promise((resolve, reject) => {
                    console.info(`started`);
                    const xhr = new XMLHttpRequest();
                    xhr.open(`GET`, this.url);

                    xhr.onload = () => {
                        if (xhr.status >= 400){
                            reject(xhr.response)
                        }else{
                            resolve(JSON.parse(xhr.response))
                        }
                    };

                    xhr.onerror = () => {
                        reject(xhr.response);
                    };

                    xhr.send()
                })
            }
        }

        class User {
            constructor(userInfo){
                this.userInfoObject = userInfo
            }
            render(){
                return `
                    <div class="user">
                        <h3>${this.userInfoObject.name}</h3>
                        <h4>${this.userInfoObject.username}</h4>
                    </div>
                `
            }
        }

        const userContainer = document.getElementById('user-container');

        document.getElementById('btn-show-users').addEventListener("click", () =>{
           const usersList = new UserList('http://jsonplaceholder.typicode.com/users', userContainer);
           usersList.getUsers()
        });
     </script>
   </body>
</html>
  • Вопрос задан
  • 100 просмотров
Решения вопроса 1
@tsuinkotei
Потому что метод renderUsers вызывается до того, как зарезолвится промис из aplleUsers. В результате forEach будет вызван на пустом массиве. Вам следует вызвать renderUsers в then коллбэке.

getUsers(){
    this.appleUsers()
        .then(result => {
            this.allUsers.push(...result);
            this.renderUsers();
         })           
        .catch(err => console.error(err));
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы