Execution after HTTP response

Example of code that won't execute after an HTTP response is sent.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

#include <google/cloud/functions/http_request.h>
#include <google/cloud/functions/http_response.h>
#include <future>

namespace gcf = ::google::cloud::functions;

gcf::HttpResponse concepts_after_response(
    gcf::HttpRequest /*request*/) {  // NOLINT
  (void)std::async(std::launch::async, [] {
    // This code may fail to complete, or even fail to start at all.
    auto constexpr kIterations = 10;
    int sum = 0;
    for (int i = 0; i != kIterations; ++i) sum += i;
    return sum;
  });
  return gcf::HttpResponse{}.set_payload("Hello World!");
}

Node.js

/**
 * HTTP Cloud Function that may not completely
 * execute due to early HTTP response
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
exports.afterResponse = (req, res) => {
  res.end();

  // This statement may not execute
  console.log('Function complete!');
};

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.