title: How to make inner async request complete first before completing outer async request in Swift?
body: <p>I've been trying to achieve this for some time and cannot get it to work.</p>
  
  <p>First let me show a simple sample code:</p>
  
  <pre><code>override func viewDidLoad()
  {
      super.viewDidLoad()
  
      methodOne("some url bring")
  }
  
  func methodOne(urlString1: String)
  {
      let targetURL = NSURL(string: urlString1)
  
      let task = NSURLSession.sharedSession().dataTaskWithURL(targetURL!) {(data, response, error) in
  
          // DO STUFF
          j = some value
  
          print("Inside Async1")
          for k in j...someArray.count - 1
          {  
              print("k = \(k)")
              print("Calling Async2")
              self.methodTwo("some url string")
          }
  
      }
  
      task.resume()
  }
  
  func methodTwo(urlString2: String)
  {
      let targetURL = NSURL(string: urlString2)
  
      let task = NSURLSession.sharedSession().dataTaskWithURL(targetURL!) {(data, response, error) in
  
          // DO STUFF
          print("inside Async2")
      }
  
      task.resume()
  }
  </code></pre>
  
  <p>What I'm basically doing is I perform an asynchronous request within my <code>methodOne</code>, and within that function, I call my <code>methodTwo</code> which performs another asynchronous request. </p>
  
  <p>The problem I'm having is that when <code>methodTwo</code> is called, it never enters the asynchronous session. It does however, within <code>methodTwo</code>, enter the asynchronous session, but only once <code>k = someArray.count - 1</code>. It's basically queuing up until the very end, which is not what I'd like to achieve.</p>
  
  <p>Here's a sample output:</p>
  
  <pre><code>Inside Async1
  k = 0
  Calling Async2
  Inside Async1
  k = 0
  Calling Async2
  k = 1
  Calling Async2
  Inside Async1
  k = 0
  Calling Async2
  k = 1
  Calling Async2
  k = 2
  Calling Async2
  Inside Async1
  .....
  Inside Async1
  k = 0
  Calling Async2
  k = 1
  Calling Async2
  k = 2
  Calling Async2
  k = 3
  Calling Async2
  k = 4
  Inside Async2
  </code></pre>
  
  <p>In other words, I'd like to have the async request from <code>methodTwo</code> complete on each iteration before the async request from <code>methodOne</code> completes.</p>
  
  <p>Here's a sample output of what my goal is:</p>
  
  <pre><code>Inside Async1
  k = 0
  Calling Async2
  Inside Async2
  Inside Async1
  k = 1
  Calling Async2
  Inside Async2
  Inside Async1
  ...
  </code></pre>
  
  <p>I've found something similar here: <a href="https://stackoverflow.com/questions/33058123/wait-until-first-async-function-is-completed-then-execute-the-second-async-funct">Wait until first async function is completed then execute the second async function</a></p>
  
  <p>However, I couldn't get this to work with the suggestions and solutions.</p>
  
  <p>Can someone point me in the right direction?</p>
  
  <p>Thanks</p>