title: Pass context through composed promises in KJ
body: <p>Playing with the KJ library, I wrote a small TCP servers that reads a &quot;PING&quot; and responds a &quot;PONG&quot;. I managed to compose the promises like this:</p>
  <pre class="lang-cpp prettyprint-override"><code>char buffer[4];
  kj::Own&lt;kj::AsyncIoStream&gt; clientStream;
  
  addr-&gt;listen()-&gt;accept()
      .then([&amp;buffer, &amp;clientStream](kj::Own&lt;kj::AsyncIoStream&gt; stream) {
        clientStream = kj::mv(stream);
        return clientStream-&gt;tryRead(buffer, 4, 4);
      }).then([&amp;buffer, &amp;clientStream](size_t read) {
        KJ_LOG(INFO, kj::str(&quot;Received&quot;, read, &quot; bytes: &quot;, buffer));
        return clientStream-&gt;write(&quot;PONG&quot;, 4);
      }).wait(waitScope);
  </code></pre>
  <p>I had to keep <code>buffer</code> out of the promises and pass a reference to it. This means that <code>buffer</code> has to stay in scope until the last promise finishes. That's the case here, but is there a solution in case it isn't?</p>
  <p>Same thing for <code>clientStream</code>: I had to declare it before, then wait until I receives it from <code>accept()</code>, and at this point move it outside and use the reference to it.</p>
  <p>Is there a better way to do it? Say like a way to pass some kind of context from promise to promise, always owned by the promises and therefore not having to stay &quot;outside&quot;?</p>