title: Javascript - How to use fetch inside a for loop and wait for results
body: <p>I am new to asynchronous functions, and I am trying to dynamically create an unordered list (ul) containing list items (li) with a child span element in each li. The span contains information coming from a mongo db. I want the for loop to wait for the results in each iteration before continuing. How do I modify this to accommodate the asynchronous operation of fetch?</p>
  <p>Thanks in advance.</p>
  <pre><code>$('.add').on(&quot;input&quot;, function() {
  
  var table = document.getElementById(&quot;table&quot;).getElementsByTagName('tbody')[0];
  
  //Input text
  var searchInput = this.value;
  
  var searched_ul = document.getElementById('searched_ul');
  
  fetch(&quot;______&quot;,{
  }).then(response =&gt; {
      return response.json();
  }).then(data =&gt; {
  
      for(var i=0; i&lt;data.length; i++){
  
          if(capitalizeFirstLetter(data[i].name).startsWith(capitalizeFirstLetter(searchInput)) &amp;&amp; searchInput != ''){
  
              var searched_li = document.createElement('li');
              searched_li.innerHTML = data[i].name;
  
              //Outputs all the names from the for loop as expected, but fetch only does last item
              console.log(&quot;NAME&quot;, data[i].name);
  
              //Span child element containing info
              var dep_span = document.createElement('span');
              //Add css class for styling
              dep_span.classList.add('dep-span');
  
              fetch(&quot;_______&quot; + data[i].d,{
              }).then(response =&gt; {
                  return response.json();
              }).then(depData =&gt; {
                  dep_span.innerHTML = depData.name;
  
                  //Outputs li and span for last item in for loop (i times)
                  console.log(&quot;LI: &quot;, searched_li);
  
                  //Append span to li
                  searched_li.appendChild(dep_span);
              });
  
  
              searched_li.addEventListener(&quot;click&quot;, function(e){
  
              });
              searched_ul.append(searched_li);
          }
      }
  
  }).catch(function(err){
      console.log(err);
  });
  });
  </code></pre>