title: Prevent context cancel from stopping function execution in the middle of business logic
body: <p>Is there a way to safeguard the execution of business logic from context cancel? Here is the code snippet for a better understanding of my problem</p>
  <pre><code>func main() {
      ctx, cancel := context.WithCancel(context.Background())
      go foo(ctx)
      time.Sleep(time.Second * 3)
      cancel()
  }
  
  func foo(ctx context.Context) {
      // batch process data
      // context cancel should not stop function execution 
      // in the middle of business logic
      for i:= 0; i&lt;10; i++ {
          fmt.Println(&quot;START of business logic for ID:&quot;, i)
          fmt.Println(&quot;Critical component&quot;)
          fmt.Print(&quot;Saving changes to DB...&quot;)
          time.Sleep(time.Second * 1)
          fmt.Println(&quot;Done&quot;)
          fmt.Println(&quot;END of business logic for ID:&quot;, i)
      }
  }
  </code></pre>
  <p>Output:</p>
  <pre><code>START of business logic for ID: 0
  Critical component
  Saving changes to DB...Done
  END of business logic for ID: 0
  START of business logic for ID: 1
  Critical component
  Saving changes to DB...Done
  END of business logic for ID: 1
  START of business logic for ID: 2
  Critical component
  Saving changes to DB...Done
  END of business logic for ID: 2
  </code></pre>
  <p>When the execution starts in the for loop, it should not stop until it finishes that iteration. Is this possible with using context cancel? or should I use another approach, please suggest.</p>
  <p><a href="https://play.golang.org/p/YSSphRNfl8H" rel="nofollow noreferrer">Go Playground Link</a></p>