Get Pens from CodePen API (using Handlebars & async/await)

Get pens from unofficial CodePen API using Handlebars, async/await, fetch.

by Konstantin Rouda

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.js"></script>
<ul class="c-list" id="list">
</ul>


<script type="text/x-handlebars-template" id="template">
   <li class="c-list__item jsListItem">
     <div class="c-pen">
        <h4 class="c-pen__title"><a href="{{link}}" class="c-pen__link">{{title}}</a></h4>
        <img src="{{images.small}}" />
     </div>
   </li>
</script>

JavaScript

;(function() {
    "use strict";
    
    const list = document.getElementById("list");
    const templateWrapper = document.getElementById("template");
    
    const URL = "https://cpv2api.com/pens/public/Konrud";
    
    /*
    * Gets pens according to the received url
    * @param {String} url - URL to get data from
    * @return {Array} - Array of data
    */
    async function getPens (url) {
       let pens = {};
       try {
          const result = await fetch(url);
          debugger;
          pens = await result.json();
       } catch (err) {
          debugger;
       }
       return pens.data;  
    };
 
   /*
   * Fills received list with data from the provided url
   * @param {HTMLElement} list - HTML element to fill with data
   * @param {String} url - URL to get data from
   */
   async function fillListWithData (list, url) {

        const pens = await getPens(url);

        pens.forEach(function(penItem) {
            const template = getTemplate(penItem);
            if(template) {
              list.insertAdjacentHTML("beforeend", template);
            }
        });

   }; 
 
    
    /*
    * Create HTML template for the received data object (Using Handlebars)
    * @param {Object} dataObj - Object with data to fill the template
    * @return {String} - HTML template in string representation
    */
    function getTemplate (dataObj) {
       debugger;
       if(templateWrapper.innerHTML) {
          const handlebarsTemplate = Handlebars.compile(templateWrapper.innerHTML)(dataObj);
          return handlebarsTemplate;
       }
    };
    
    
    fillListWithData(list, URL);
    
})();