用异步Promise追加div

时间:2018-11-05 17:38:34

标签: javascript async-await

我正在尝试使用Firebase从阵列中打印名称和位置的列表。我正在使用异步调用对数组进行变异,但是在将数据打印到页面之前,我不知道如何等待结果。

记录数组显示数据正确,但是在添加div后

// Start with an array of course objects from Firebase and loop through each 
// course: {
//    title: 'Some title',
//     start: {Date},
//     users: {
//       uid1: {
//         name: 'Person 1',
//         email: 'person1@email.com'
//       },
//       uid2: { ... }
//     }
//   }       

    courses.forEach(function(course) {

        // Destructure the course object for easier handling
        let { title, users } = course;

        // Map the users in the course into an array for looping
        let userArray = Object.values(users).map(function(key) {
          return key
        });

        // Look up the user building in another ref
        userArray.map(async function(user) {
          let building = await firebase.database().ref('users/').orderByChild('email').equalTo(user.email).once('value', snapshot => {
              snapshot.forEach(async function(child) {
                return user.building = child.val().building;
              })
          });
        })

        // Shows the array correctly, but _after_ the function has finished
        console.log(userArray)

        // Create a container to hold the results
        let container = document.createElement('div');

        // Set a template literal loop inside the forEach to make variable assignment simple
        // See more at https://gist.github.com/wiledal/3c5b63887cc8a010a330b89aacff2f2e

    container.innerHTML =
        `
            <span class="wkshp-title"><h5>${ course.title }</h5></span>
            <span class="wkshp-date"><h6>${ course.start }</h6></span>
            <div class="users">
              <ul class="user-list">
              ${ userArray.map((item) =>
                 `<li><span>${ item.name }</span><span>${ item.building }</span></li>`).join('') 
               }
              </ul>
            </div>
        `
        // Append the child array to the parent
        parent.appendChild(container);
      })
    })

0 个答案:

没有答案