title: How to make synchronous API call in coroutines?
body: <p>I need to call API in for loop for each element, but it has to wait for each API call to return values, because if it will be asynchronous, order of returned elements could be mixed because each of those requests are asynchronous calls. </p>
  
  <p>I want to wait inside for loop till value is returned. I used <code>await()</code> for this but it is not working as expected. Results are returned after for loop.</p>
  
  <p>Code:</p>
  
  <pre><code>parts.forEach {p-&gt;
              if (p.listEmpty){
                  validItems.add(PartItem(TYPE_WITHOUT_LIST, p))
              } else {
                  launch {
                      val listReturned = getItemsForPart(p)
                      validItems.add(PartItem(TYPE_WITH_LIST, p, listReturned))
                  }
              }
  }
  
  private val scope = CoroutineScope(Dispatchers.IO)
  private suspend fun getItemsForPart(p: InnerItemPart): List&lt;InnerPart&gt;{
          val partResp = CompletableDeferred&lt;List&lt;InnerPart&gt;&gt;()
          scope.launch{
              val parent = api.getParentOfPart(p.partId)
              var filteredParts = emptyList&lt;InnerPart&gt;()
              if (parent != null){
                  val startIndex = parent.innerPart.indexOfFirst { it.partId == p.startId }
                  val endIndex = parent.innerPart.indexOfFirst { it.partId == p.endId }
                  filteredParts = parent.subList(startIndex, endIndex).toMutableList()
                  if (filteredParts.isNotEmpty()) filteredPart.removeAt(0)
              }
              partResp.complete(filteredParts)
          }
  
          return partResp.await()
  }
  </code></pre>